use std::{env, process::Command, thread, time::Duration};

// const WIDTH: u32 = 7;
// const HEIGHT: u32 = 7;
const WIDTH: u32 = 14;
const HEIGHT: u32 = 13;
const CHUNK_W: u32 = 1280 / WIDTH;
const CHUNK_H: u32 = 1000 / HEIGHT;
const _SIZE: u32 = WIDTH * HEIGHT;
// const SCALE: u32 = 2; // resolution of chunks
const OFFSET: f32 = 0.1; // time offset for starting

fn main() {
	let args: Vec<_> = env::args().collect();
	if args.contains(&"gen".into()) {
		generate();
	} else {
		launch();
	}
}

fn generate() {
	for x in 0..WIDTH {
		for y in 0..HEIGHT {
			let name = format!("out/{x:02}_{y:02}.mp4");
			let index = (WIDTH - x) + (HEIGHT - y) * WIDTH;
			let offset = index as f32 * OFFSET;
			// println!("{name}");

			// if PathBuf::from(&name).exists() {
			// 	continue;
			// }
			Command::new("ffmpeg")
				.arg("-i")
				.arg("bad_apple.webm")
				.arg("-ss")
				.arg(format!("{:.1}", offset))
				.arg("-filter_complex")
				.arg(dbg!(format!(
					"[0:v]scale=1280:1000[SC];[SC]crop={}:{}:{}:{}",
					CHUNK_W,
					CHUNK_H,
					x * CHUNK_W,
					y * CHUNK_H
				)))
				.arg("-an")
				.arg("-y")
				.arg(&name)
				.spawn()
				.unwrap();
		}
	}
}

fn launch() {
	thread::sleep(Duration::from_secs(2));
	Command::new("mpv")
		.arg(format!("bad_apple_audio.webm"))
		.spawn()
		.unwrap();
	for y in (0..HEIGHT).rev() {
		for x in (0..WIDTH).rev() {
			let name = format!("out/{x:02}_{y:02}.mp4");
			Command::new("mpv").arg(name).spawn().unwrap();
			thread::sleep(Duration::from_millis((1000.0 * OFFSET) as u64));
		}
	}
}
