//! Render the drum-notation view (pm-ui) for a parsed groove → PNG. `cargo run --bin notesim [prog]`.

use embedded_graphics::{pixelcolor::Rgb565, prelude::*};
use pm_ui::{LaneView, Screen};

const W: u32 = 320;
const H: u32 = 480;

struct Fb {
    px: Vec<Rgb565>,
}
impl DrawTarget for Fb {
    type Color = Rgb565;
    type Error = core::convert::Infallible;
    fn draw_iter<I: IntoIterator<Item = Pixel<Rgb565>>>(&mut self, pixels: I) -> Result<(), Self::Error> {
        for Pixel(p, c) in pixels {
            if p.x >= 0 && p.y >= 0 && (p.x as u32) < W && (p.y as u32) < H {
                self.px[(p.y as u32 * W + p.x as u32) as usize] = c;
            }
        }
        Ok(())
    }
}
impl OriginDimensions for Fb {
    fn size(&self) -> Size {
        Size::new(W, H)
    }
}

fn main() {
    // args: [prog] [view]  where view ∈ staff|tubs|konnakol (default staff)
    let prog = std::env::args().nth(1).unwrap_or_else(|| "t96;kick:4=X.x.;snare:4=.X.X;hatClosed:4/2=xxxxxxxx".into());
    let view = match std::env::args().nth(2).as_deref() {
        Some("tubs") => pm_ui::ViewMode::Tubs,
        Some("konnakol") | Some("kon") => pm_ui::ViewMode::Konnakol,
        _ => pm_ui::ViewMode::Staff,
    };
    let track = track_format::parse(&prog);
    let lanes: Vec<LaneView> = track
        .lanes
        .iter()
        .map(|l| LaneView { name: &l.sound, levels: &l.levels, orns: &l.orns, groups: &l.groups, beats: l.groups.iter().sum::<u32>().min(255) as u8, poly: l.poly, muted: l.mute })
        .collect();
    let screen = Screen { name: "Rock beat", bpm: track.bpm, playing: false, phase: 0.0, lanes: &lanes };

    let mut fb = Fb { px: vec![Rgb565::BLACK; (W * H) as usize] };
    pm_ui::notation::draw(&mut fb, &screen, view).unwrap();

    let img = image::RgbImage::from_fn(W, H, |x, y| {
        let c = fb.px[(y * W + x) as usize];
        image::Rgb([(c.r() << 3) | (c.r() >> 2), (c.g() << 2) | (c.g() >> 4), (c.b() << 3) | (c.b() >> 2)])
    });
    img.save("notation.png").unwrap();
    println!("wrote notation.png for: {prog}");
}
