use std::io::Read;

use blurhash_update::{Components, Encoder, ImageBounds};
use clap::Parser;

#[derive(clap::Parser)]
struct Args {
    /// Width of the provided image
    #[clap(long)]
    width: u32,

    /// Height of the provided image
    #[clap(long)]
    height: u32,

    #[clap(long)]
    skip: Option<u32>,
}

// Example usage:
// ```bash
// magick convert /path/to/image RGBA:- | \
//     cargo r --example --release -- --width blah --height blah
// ```
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let Args {
        width,
        height,
        skip,
    } = Args::parse();

    let mut encoder = if let Some(skip) = skip {
        Encoder::new(
            Components { x: 4, y: 3 },
            ImageBounds { width, height },
            skip,
        )?
    } else {
        Encoder::auto(ImageBounds { width, height })
    };

    let mut stdin = std::io::stdin().lock();
    let mut buf = [0u8; 1024];

    loop {
        let n = stdin.read(&mut buf)?;

        if n == 0 {
            break;
        }

        encoder.update(&buf[..n]);
    }

    println!("{}", encoder.finalize());

    Ok(())
}
