use core::{
    marker::PhantomData,
    slice::{from_raw_parts, from_raw_parts_mut},
};

use crate::Dim;

macro_rules! impl_iter (
    ($dr_matrix_iter:ident, $data_ptr:ty, $data_type:ty, $from_raw_parts:ident) => (
#[derive(Debug)]
pub struct $dr_matrix_iter<'a, T: 'a> {
    curr_row: usize,
    data: $data_ptr,
    dim: Dim<[usize; 2]>,
    phantom: PhantomData<&'a T>,
}

impl<'a, T> $dr_matrix_iter<'a, T> {
    pub(crate) fn new(
        dim: [usize; 2],
        data: $data_ptr,
    ) -> Self {
        $dr_matrix_iter {
            curr_row: 0,
            data,
            dim: dim.into(),
            phantom: PhantomData,
        }
    }

    pub fn split_at(self, idx: usize) -> (Self, Self) {
        let current_len = self.dim.rows() - self.curr_row;
        assert!(idx <= current_len);
        let slice_point = self.curr_row + idx;
        (
            $dr_matrix_iter {
                curr_row: self.curr_row,
                data: self.data,
                dim: [slice_point, self.dim.cols()].into(),
                phantom: PhantomData,
            },
            $dr_matrix_iter {
                curr_row: slice_point,
                data: self.data,
                dim: self.dim,
                phantom: PhantomData,
            }
        )
    }
}

impl<'a, T> DoubleEndedIterator for $dr_matrix_iter<'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.curr_row >= self.dim.rows() {
            return None;
        }
        let data: $data_type = unsafe {
            let offset = ((self.dim.rows() - 1) * self.dim.cols()) as isize;
            let ptr = self.data.offset(offset);
            $from_raw_parts(ptr, self.dim.cols())
        };
        *self.dim.rows_mut() -= 1;
        Some(data)
    }
}

impl<'a, T> ExactSizeIterator for $dr_matrix_iter<'a, T> {
}


impl<'a, T> Iterator for $dr_matrix_iter<'a, T> {
    type Item = $data_type;

    fn next(&mut self) -> Option<Self::Item> {
        if self.curr_row >= self.dim.rows() {
            return None;
        }
        let data: $data_type = unsafe {
            let offset = (self.curr_row * self.dim.cols()) as isize;
            let ptr = self.data.offset(offset);
            $from_raw_parts(ptr, self.dim.cols())
        };
        self.curr_row += 1;
        Some(data)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.dim.rows(), Some(self.dim.rows()))
    }
}

unsafe impl<'a, T> Send for $dr_matrix_iter<'a, T> {}
unsafe impl<'a, T> Sync for $dr_matrix_iter<'a, T> {}

    );
);

impl_iter!(DrMatrixRowIter, *const T, &'a [T], from_raw_parts);
impl_iter!(DrMatrixRowIterMut, *mut T, &'a mut [T], from_raw_parts_mut);
