use super::types::{Color, PSXImageConverter};

pub struct RgbImage {
    raw_data: std::vec::IntoIter<u8>,
    width:    u16,
    height:   u16,
}

impl RgbImage {
    pub fn new(image: image::RgbImage) -> RgbImage {
        let width    = image.width() as u16;
        let height   = image.height() as u16;
        let raw_data = image.into_raw().into_iter();

        RgbImage{raw_data, width, height}
    }
}

impl PSXImageConverter for RgbImage {
    fn width(&self) -> u16 {
        self.width
    }

    fn height(&self) -> u16 {
        self.height
    }

    fn get_palette(&self) -> Option<&Vec<Color>> {
        None
    }
}

impl std::iter::Iterator for RgbImage {
    type Item = Color;

    fn next(&mut self) -> Option<Self::Item> {
        let r = self.raw_data.next()?;
        let g = self.raw_data.next()?;
        let b = self.raw_data.next()?;

        Some(Color::non_transparent(r, g, b))
    }
}

pub struct RgbaImage {
    raw_data: std::vec::IntoIter<u8>,
    width:    u16,
    height:   u16,
}

impl RgbaImage {
    pub fn new(image: image::RgbaImage) -> RgbaImage {
        let width    = image.width() as u16;
        let height   = image.height() as u16;
        let raw_data = image.into_raw().into_iter();

        RgbaImage{raw_data, width, height}
    }
}

impl PSXImageConverter for RgbaImage {
    fn width(&self) -> u16 {
        self.width
    }

    fn height(&self) -> u16 {
        self.height
    }

    fn get_palette(&self) -> Option<&Vec<Color>> {
        None
    }
}

impl std::iter::Iterator for RgbaImage {
    type Item = Color;

    fn next(&mut self) -> Option<Self::Item> {
        let r = self.raw_data.next()?;
        let g = self.raw_data.next()?;
        let b = self.raw_data.next()?;
        let a = self.raw_data.next()?;

        Some(
            match a {
                0x0  => Color::transparent(),
                0xFF => Color::non_transparent(r, g, b),
                _    => Color::semi_transparent(r, g, b),
            }
        )
    }
}