use adw::prelude::*;
use gio::resources_lookup_data;
use glib::IsA;
use gtk::STYLE_PROVIDER_PRIORITY_USER;
use l10n::{L10N, NonEmptyList};
use std::path::PathBuf;
use crate::messages;

mod chat;
pub use chat::Chat;

mod config;
pub use config::ConfigurationPage;

mod game_preview;
pub use game_preview::GamePreview;

mod library;
pub use library::Library;

mod player_card;
pub use player_card::PlayerCard;

mod playing_field;
pub use playing_field::PlayingField;

mod home;
pub use home::Home;

mod board;
pub use board::Board;

#[cfg(feature = "screenplay")]
pub use playing_field::playing_field_view;

pub struct AppWindow {
    pub window: adw::ApplicationWindow,
    pub header: adw::HeaderBar,
    pub content: adw::Bin,
}

impl AppWindow {
    pub fn new(app: &adw::Application) -> Self {
        let window = adw::ApplicationWindow::builder()
            .application(app)
            .width_request(800)
            .height_request(500)
            .build();

        let stylesheet = String::from_utf8(
            resources_lookup_data(
                "/com/luminescent-dreams/kifu-gtk/style.css",
                gio::ResourceLookupFlags::NONE,
            )
            .expect("stylesheet should just be available")
            .to_vec(),
        )
        .expect("to parse stylesheet");

        let provider = gtk::CssProvider::new();
        provider.load_from_data(&stylesheet);
        let context = window.style_context();
        context.add_provider(&provider, STYLE_PROVIDER_PRIORITY_USER);

        let header = adw::HeaderBar::builder()
            .title_widget(&gtk::Label::new(Some("Kifu")))
            .build();

        let app_menu = gio::Menu::new();
        let menu_item = gio::MenuItem::new(Some("Configuration"), Some("app.show-config"));
        app_menu.append_item(&menu_item);

        let hamburger = gtk::MenuButton::builder()
            .icon_name("open-menu-symbolic")
            .build();
        hamburger.set_menu_model(Some(&app_menu));

        header.pack_end(&hamburger);

        let content = adw::Bin::builder().css_classes(vec!["content"]).build();
        let mut l10n = L10N::new(PathBuf::from("resources"));
        l10n.set_locales(NonEmptyList::from_iter(vec!["en-US", "eo"]).unwrap());
        content.set_child(Some(
            &adw::StatusPage::builder().title(l10n.tr(messages::NothingHere)).build(),
        ));

        let layout = gtk::Box::builder()
            .orientation(gtk::Orientation::Vertical)
            .build();
        layout.append(&header);
        layout.append(&content);

        window.set_content(Some(&layout));

        Self {
            window,
            header,
            content,
        }
    }

    pub fn set_content(&self, content: &impl IsA<gtk::Widget>) {
        self.content.set_child(Some(content));
    }
}