use tauri::{
    App,
    AppHandle,
    Manager,
    async_runtime as rt,
};
use tauri::menu::{
    MenuBuilder,
    MenuEvent,
    MenuItemBuilder,
};

use crate::app;
use crate::state::AppState;


pub fn setup(app: &App) -> tauri::Result<()> {
    let show_hide = MenuItemBuilder::with_id("show_hide", "Show").build(app)?;
    let exit = MenuItemBuilder::with_id("exit", "Exit").build(app)?;

    let menu = MenuBuilder::new(app)
        .items(&[&show_hide, &exit])
        .build()?;

    let tray = app.tray_by_id("main").unwrap();
    tray.set_menu(Some(menu))?;
    tray.on_menu_event(handle_event);

    // stash this so we can find it later to change the text
    app.manage(show_hide);

    Ok(())
}


fn handle_event(app_handle: &AppHandle, event: MenuEvent) {
    match event.id.0.as_str() {
        "exit" => app_handle.exit(0),
        "show_hide" => {
            let _ = app::toggle_main_window(app_handle);
            let new_handle = app_handle.clone();
            rt::spawn(async move {
                let state = new_handle.state::<AppState>();
                state.signal_activity().await;
            });
        },
        _ => (),
    }
}
