use std::{fs::File, io::{Cursor, Write}};

use crate::{protocol::{ProtocolReader, ProtocolWriter}, quality_settings::QualitySettings};

mod compression;
mod constants;
mod decompression;
mod png_utils;
mod protocol;
mod quality_settings;
mod quantization;
mod transform;
mod image;


fn main() {
    // run_for("zonked".to_string(), 9, 2, Some(330000));
    run_for("zonked".to_string(), 9, 2, Some(37000));
    run_for("avatar2".to_string(), 9, 2, Some(100000));
}
fn run_for(name: String, quality_rgb: u8, quality_alpha: u8, bytes_to_chop: Option<usize>) {
    let image = png_utils::load_image(
        format!("inputs/{}.png", name),
        QualitySettings::new(quality_rgb),
        QualitySettings::new(quality_alpha),
    ).unwrap();
    let mut writer = ProtocolWriter::new(vec![]);

    compression::compress(
        image,
        &mut writer
    ).unwrap();
    let mut compressed = writer.destroy();

    if let Some(b2c) = bytes_to_chop {
        compressed.drain(b2c..);
    }

    let mut output_file = File::create(format!("outputs/{}.rxi", name)).unwrap();
    output_file.write_all(&compressed).unwrap();

    let mut reader = ProtocolReader::new(Cursor::new(compressed));
    let decompressed = decompression::decompress(&mut reader).unwrap();

    let decompressed_image = match decompressed {
        decompression::ProgressiveImage::Present { image, complete: _ } => {
            image
        }
        decompression::ProgressiveImage::NotHereYet => {
            // image not here yet
            println!("not here yet: {}", name);
            return
        }
    };

    png_utils::save_image(
        format!("outputs/{}_out.png", name), 
        decompressed_image
    ).unwrap();
}
