use muda::{Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem, Submenu};
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub enum MenuAction {
    SystemInfo,
}

pub struct NativeMenu {
    menu: Menu,
    action_map: HashMap<MenuId, MenuAction>,
    attached: bool,
}

impl NativeMenu {
    pub fn init() -> Self {
        let menu = Menu::new();
        let mut action_map = HashMap::new();

        let app_menu = Submenu::new("Cue", true);
        let _ = app_menu.append(&PredefinedMenuItem::about(None, None));
        let _ = app_menu.append(&PredefinedMenuItem::separator());

        let sys_info = MenuItem::new("System Info", true, None::<muda::accelerator::Accelerator>);
        action_map.insert(sys_info.id().clone(), MenuAction::SystemInfo);
        let _ = app_menu.append(&sys_info);

        let _ = app_menu.append(&PredefinedMenuItem::separator());
        let _ = app_menu.append(&PredefinedMenuItem::quit(None));

        let _ = menu.append(&app_menu);

        Self {
            menu,
            action_map,
            attached: false,
        }
    }

    pub fn ensure_attached(&mut self) {
        if !self.attached {
            #[cfg(target_os = "macos")]
            self.menu.init_for_nsapp();
            self.attached = true;
        }
    }

    pub fn poll_events(&mut self) -> Vec<MenuAction> {
        self.ensure_attached();
        let mut actions = Vec::new();
        while let Ok(event) = MenuEvent::receiver().try_recv() {
            if let Some(action) = self.action_map.get(event.id()) {
                actions.push(action.clone());
            }
        }
        actions
    }
}
