use serde::{Serialize, Deserialize};

use tauri::{
    GlobalShortcutManager,
    Manager,
    async_runtime as rt,
};

use crate::app::APP;
use crate::config::HotkeysConfig;
use crate::errors::*;
use crate::terminal;


#[derive(Debug, Serialize, Deserialize)]
pub enum ShortcutAction {
    ShowWindow,
    LaunchTerminal,
}


pub fn exec_shortcut(action: ShortcutAction) {
    match action {
        ShortcutAction::ShowWindow => {
            let app = APP.get().unwrap();
            app.get_window("main")
                .ok_or("Couldn't find application main window")
                .map(|w| w.show().error_popup("Failed to show window"))
                .error_popup("Failed to show window");
        },
        ShortcutAction::LaunchTerminal => {
            rt::spawn(async {
                terminal::launch(false).await.error_popup("Failed to launch terminal");
            });
        },
    }
}


pub fn register_hotkeys(hotkeys: &HotkeysConfig) -> tauri::Result<()> {
    let app = APP.get().unwrap();
    let mut manager = app.global_shortcut_manager();
    manager.unregister_all()?;

    if hotkeys.show_window.enabled {
        manager.register(
            &hotkeys.show_window.keys,
            || exec_shortcut(ShortcutAction::ShowWindow)
        )?;
    }

    if hotkeys.launch_terminal.enabled {
        manager.register(
            &hotkeys.launch_terminal.keys,
            || exec_shortcut(ShortcutAction::LaunchTerminal)
        )?;
    }

    Ok(())
}
