#![cfg_attr(target_arch = "wasm32", allow(dead_code, unused_imports))]

#[cfg(not(target_arch = "wasm32"))]
mod native {
    use std::{path::PathBuf, process::ExitCode, time::Duration};

    use game_audio::{SoundSystem, track::SongPlayer};

    pub fn run() -> ExitCode {
        let mut args = std::env::args().skip(1);
        let Some(input) = args.next().map(PathBuf::from) else {
            eprintln!("Usage: track-play <input.track> [speed]");
            return ExitCode::FAILURE;
        };
        let speed = match args.next() {
            Some(text) => match text.parse::<f32>() {
                Ok(speed) if speed > 0.0 => speed,
                _ => {
                    eprintln!("Invalid speed '{text}' (expected a positive number)");
                    return ExitCode::FAILURE;
                }
            },
            None => 1.0,
        };

        let system = SoundSystem::new();
        if !system.is_active() {
            eprintln!("No audio device available");
            return ExitCode::FAILURE;
        }

        let mut player = SongPlayer::new();
        if let Err(error) = player.play_path(&system, &input) {
            eprintln!("Playing {input}: {error}", input = input.display());
            return ExitCode::FAILURE;
        }
        player.set_speed(speed);

        eprintln!("Playing {input} (Ctrl+C to stop)", input = input.display());
        while player.is_playing() {
            std::thread::sleep(Duration::from_millis(50));
        }
        ExitCode::SUCCESS
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn main() -> std::process::ExitCode {
    native::run()
}

#[cfg(target_arch = "wasm32")]
fn main() {}
