use std::fs::File;
use std::io::BufReader;
use crate::pixel::Pixel;
/// Represents the data decoded from a PNG file, with pre-computed pixel data.
pub struct PngData {
    pub width: u32,
    pub height: u32,
    pub packed_pixels: Vec<Pixel>,
}
impl PngData {

    pub fn open(path: &str) -> Result<Self, png::DecodingError> {
        let file = File::open(path).expect("Failed to open PNG file");
        let decoder = png::Decoder::new(BufReader::new(file));
        let mut reader = decoder.read_info()?;
        let mut buf = vec![0; reader.output_buffer_size()];
        let info = reader.next_frame(&mut buf)?;

        let width = info.width;
        let height = info.height;

        let mut packed_pixels = Vec::new();
        for sy in 0..height {
            for sx in 0..width {
                let index = (sy * width + sx) as usize * 4;
                let a = buf[index + 3];
                if a > 0 {
                    let r = buf[index];
                    let g = buf[index + 1];
                    let b = buf[index + 2];
                    let x = sx as u16;
                    let y = sy as u16;
                    packed_pixels.push(Pixel {
                        x,
                        y,
                        r,
                        g,
                        b
                    })
                }
            }
        }

        eprintln!(
            "[png] {}: {}x{}, {} opaque pixels pre-computed",
            path, width, height, packed_pixels.len()
        );

        Ok(PngData {
            width,
            height,
            packed_pixels,
        })
    }
}
