use image::{imageops, GenericImage, ImageBuffer, Pixel};

use super::{Image, ResizableImage, RGB};

impl<I, P> Image for I
where
    I: GenericImage<Pixel = P> + 'static,
    P: Pixel<Subpixel = u8> + 'static,
{
    fn width(&self) -> u32 {
        self.width()
    }

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

    fn get(&self, x: u32, y: u32) -> RGB {
        let px = self.get_pixel(x, y).to_rgb();

        let r = px[0];
        let g = px[1];
        let b = px[2];
        RGB { r, g, b }
    }
}

impl<I, P> ResizableImage<ImageBuffer<P, std::vec::Vec<u8>>> for I
where
    I: GenericImage<Pixel = P> + 'static,
    P: Pixel<Subpixel = u8> + 'static,
{
    fn resize(&self, width: u32, height: u32) -> ImageBuffer<P, std::vec::Vec<u8>> {
        imageops::resize(self, width, height, imageops::FilterType::Triangle)
    }

    fn crop_and_resize(&self, crop: crate::Crop, width: u32, height: u32) -> ImageBuffer<P, std::vec::Vec<u8>> {
        let cropped = imageops::crop_imm(self, crop.x, crop.y, crop.width, crop.height);
        imageops::resize(cropped.inner(), width, height, imageops::FilterType::Triangle)
    }
}
