use std::{
    env::{self, args},
    path::Path,
    process::Command,
    thread::sleep,
    time::Duration,
};

use daemonize::Daemonize;

fn main() {
    let args: Vec<String> = args().collect();
    let timeout: u64 = args.get(1)
        .expect("There should be at least 1 argument, which specifies amount of time (in seconds) for timer to work!")
        .parse()
        .expect("The first argument should be a non-negative integer number");
    let measurement: char = args
        .get(2)
        .map_or('s', |arg| arg.chars().next().unwrap_or('s'));
    let sleeping_amount: Duration = match measurement {
        's' => Duration::from_secs(timeout),
        'm' => Duration::from_mins(timeout),
        _ => panic!("Invalid measurement of time! For now, only 's' and 'm' are supported"),
    };

    let current_exe_path = env::current_exe().unwrap().canonicalize().unwrap();
    let root = current_exe_path
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .parent()
        .unwrap();
    let alert_path = args.get(3).map_or_else(
        || {
            let default = "assets/not_sussy_song.opus";
            let default_path = root.join(default);
            if !default_path.exists() {
                let _ = Command::new("zenity")
                    .args([
                        "--error",
                        &format!(
                            "--text=Bundled alarm sound wasn't found! path: {}",
                            default_path.to_str().unwrap()
                        ),
                    ])
                    .spawn()
                    .unwrap()
                    .wait();
                panic!("Didn't find bundled sound");
            }
            default
        },
        |path| {
            assert!(
                Path::new(path).exists(),
                "The path provided should point to an existing file"
            );
            path
        },
    );

    Daemonize::new().working_directory(root).start().unwrap();

    sleep(sleeping_amount);

    let mut sound_alert = Command::new("pw-play")
        .arg(alert_path)
        .spawn()
        .expect("pw-play utility should be installed");

    let _ = Command::new("zenity")
        .args(["--warning", "--text=Take a break from computer!"])
        .spawn()
        .unwrap()
        .wait();

    sound_alert.kill().unwrap();
}
