//! Only MenuItem widget can be placed.

use crate::widget::menuitem::MenuItem;
use std::iter::once;

#[cfg(windows)]
pub struct MenuBar {
    menu: windows_sys::Win32::UI::WindowsAndMessaging::HMENU,
}

#[cfg(windows)]
impl MenuBar {
    pub fn new() -> Self {
        use windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu;
        unsafe {
            let menu = CreateMenu();
            Self { menu }
        }
    }

    pub fn add_menu(&self, item: MenuItem) {
        use windows_sys::Win32::UI::WindowsAndMessaging::*;
        unsafe {
            AppendMenuW(
                self.menu,
                MF_POPUP | MFT_STRING,
                item.get_menu().try_into().unwrap(),
                item.get_title()
                    .encode_utf16()
                    .chain(once(0))
                    .collect::<Vec<u16>>()
                    .as_mut_ptr(),
            );
        }
    }

    pub fn get_menu(self) -> windows_sys::Win32::UI::WindowsAndMessaging::HMENU {
        self.menu
    }
}

#[cfg(unix)]
pub struct MenuBar {
    menu: gtk::gio::Menu,
}

#[cfg(unix)]
impl MenuBar {
    pub fn new() -> Self {
        use gtk::gio::Menu;
        let menu = Menu::new();
        Self { menu }
    }

    pub fn add_menu(&self, item: MenuItem) {
        use gtk::prelude::*;
        self.menu.append_item(&item.get_menu());
    }

    pub fn get_menu(self) -> gtk::gio::Menu {
        self.menu
    }
}
