use serde::{Serialize, Deserialize};

use tauri::async_runtime as rt;

use tauri_plugin_global_shortcut::{
    GlobalShortcutExt,
    Error as ShortcutError,
};

use crate::app::{self, 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::LaunchTerminal => launch_terminal(),
        ShortcutAction::ShowWindow => {
            let app = APP.get().unwrap();
            app::show_main_window(app)
                .error_popup("Failed to show Creddy");
        },
    }
}


fn launch_terminal() {
    rt::spawn(async {
        terminal::launch(false)
            .await
            .error_popup("Failed to launch terminal")
    });
}


pub fn register_hotkeys(hotkeys: &HotkeysConfig) -> Result<(), ShortcutError> {
    let app = APP.get().unwrap();
    let shortcuts = app.global_shortcut();
    shortcuts.unregister_all([
        hotkeys.show_window.keys.as_str(),
        hotkeys.launch_terminal.keys.as_str(),
    ])?;

    if hotkeys.show_window.enabled {
        shortcuts.on_shortcut(
            hotkeys.show_window.keys.as_str(),
            |app, _shortcut, _event| {
                app::show_main_window(app).error_popup("Failed to show Creddy")
            }
        )?;
    }

    if hotkeys.launch_terminal.enabled {
        shortcuts.on_shortcut(
            hotkeys.launch_terminal.keys.as_str(),
            |_app, _shortcut, _event| launch_terminal()
        )?;
    }

    Ok(())
}
