use std::cell::RefCell;

use glib::subclass::InitializingObject;
use glib::Properties;
use gtk::subclass::prelude::*;
use gtk::{glib, prelude::*, CompositeTemplate, Label, Switch};

#[derive(CompositeTemplate, Properties, Default)]
#[properties(wrapper_type = super::LabledSwitch)]
#[template(resource = "/org/foxarmy/learn-hieroglyph/widgets/labled_switch/template.ui.xml")]
pub struct LabledSwitch {
    #[template_child]
    pub switch_obj: TemplateChild<Switch>,
    #[template_child]
    pub label_obj: TemplateChild<Label>,
    #[property(get, set)]
    label: RefCell<String>,
    #[property(get, set)]
    active: RefCell<bool>,
}

#[glib::object_subclass]
impl ObjectSubclass for LabledSwitch {
    const NAME: &'static str = "LabledSwitch";
    type Type = super::LabledSwitch;
    type ParentType = gtk::Widget;

    fn class_init(klass: &mut Self::Class) {
        klass.bind_template();
        klass.set_layout_manager_type::<gtk::BoxLayout>();
    }

    fn instance_init(obj: &InitializingObject<Self>) {
        obj.init_template();
    }
}
#[glib::derived_properties]
impl ObjectImpl for LabledSwitch {
    fn constructed(&self) {
        self.parent_constructed();

        let l: &Label = self.label_obj.as_ref();
        let s: &Switch = self.switch_obj.as_ref();
        self.obj()
            .bind_property("label", l, "label")
            .sync_create()
            .build();

        self.obj()
            .bind_property("active", s, "active")
            .sync_create()
            .build();
    }

    fn dispose(&self) {
        self.dispose_template();
    }
}

impl WidgetImpl for LabledSwitch {}
