use address::Host;
use std::path::PathBuf;

use image::ImageReader;

use clap::Parser;

mod flutr;
mod pixelmsgs;

use flutr::FlutR;
use pixelmsgs::Add;
use pixelmsgs::PixelStringMsgs;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    image_path: PathBuf,
    host: Host,

    #[arg(default_value_t = 1234)]
    port: u16,
}

fn main() {
    let args = Args::parse();

    let pixel_msgs = parse_image_to_msgs(&args.image_path);

    let mut flutr = FlutR::new(args.host, args.port, pixel_msgs).unwrap();
    flutr.flut();
}

fn parse_image_to_msgs(path: &PathBuf) -> PixelStringMsgs {
    let image_result = parse_image(path);

    let image = match image_result {
        Ok(img) => img,
        Err(err) => panic!("Error reading image! {err}"),
    };

    let rgb_image = image.into_rgb8();
    let mut result = PixelStringMsgs::with_capacity(rgb_image.len());
    for pixel in rgb_image.enumerate_pixels() {
        result.add(pixel);
    }

    result
}

fn parse_image(path: &PathBuf) -> Result<image::DynamicImage, image::error::ImageError> {
    ImageReader::open(path)?.with_guessed_format()?.decode()
}
