// SPDX-License-Identifier: GPL-3.0-or-later

//! The window handle/ title bar/ header bar.

use std::rc::Rc;

use glib::Cast;
use grx_macros::gtk_component;
use gtk::glib;
use gtk::traits::WidgetExt;
use libadwaita as adw;

use crate::{new_gc, props};

use super::gtk_props::apply;

#[props]
#[derive(Default, Debug)]
pub struct Props {
    pub title: Option<String>,
}

pub fn header_bar(mut props: Props) -> Rc<HeaderBar> {
    let hb = adw::HeaderBar::builder()
        .show_start_title_buttons(true)
        .show_end_title_buttons(true)
        .build();
    for c in &props.children {
        let a = c.annotations();
        if let Some("end") = a.get("pack").and_then(|v| v.as_str()) {
            let inner = c.clone().inner();
            let w: &gtk::Widget = inner.downcast_ref().unwrap();
            hb.pack_end(w);
        } else {
            let inner = c.clone().inner();
            let w: &gtk::Widget = inner.downcast_ref().unwrap();
            hb.pack_start(w);
        }
    }
    let comp = new_gc!(HeaderBar { hb, props });

    if let Some(title) = comp.props.title.as_ref() {
        comp.set_title(title)
    }

    apply(comp.clone());
    comp
}

#[gtk_component(libadwaita::HeaderBar)]
#[derive(Debug)]
pub struct HeaderBar {}
impl HeaderBar {
    pub fn set_title(&self, title: &str) {
        let label = gtk::Label::new(Some(title));
        label.set_ellipsize(gtk::gdk::pango::EllipsizeMode::End);
        label.add_css_class("title");
        self.widget.set_title_widget(Some(&label))
    }
}
