use gtk::{
    glib::{self, clone},
    prelude::*,
    subclass::prelude::*,
};

mod imp {
    use std::cell::OnceCell;

    use super::*;

    #[derive(Debug, Default)]
    pub struct CameraRow {
        pub label: gtk::Label,
        pub checkmark: gtk::Image,
        pub signals: OnceCell<glib::SignalGroup>,
    }

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

    impl ObjectImpl for CameraRow {
        fn constructed(&self) {
            let obj = self.obj();
            self.parent_constructed();

            let signals = glib::SignalGroup::new::<gtk::SingleSelection>();
            signals.connect_notify_local(
                Some("selected"),
                clone!(
                    #[weak]
                    obj,
                    move |selection, _| {
                        let selection = selection.downcast_ref::<gtk::SingleSelection>().unwrap();
                        if let Some(selected_item) = selection
                            .selected_item()
                            .and_downcast_ref::<super::CameraRow>()
                        {
                            obj.set_selected(selected_item == &obj);
                        } else {
                            obj.set_selected(false);
                        }
                    }
                ),
            );
            self.signals.set(signals).unwrap();

            obj.set_spacing(6);
            self.checkmark.set_icon_name(Some("object-select-symbolic"));
            self.checkmark.set_visible(false);

            obj.append(&self.label);
            obj.append(&self.checkmark);
        }
    }
    impl WidgetImpl for CameraRow {}
    impl BoxImpl for CameraRow {}
}

glib::wrapper! {
    pub struct CameraRow(ObjectSubclass<imp::CameraRow>)
        @extends gtk::Widget, gtk::Box,
        @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
}

impl Default for CameraRow {
    fn default() -> Self {
        glib::Object::new()
    }
}

impl CameraRow {
    pub fn set_label(&self, label: &str) {
        self.imp().label.set_label(label);
    }

    fn set_selected(&self, selected: bool) {
        self.imp().checkmark.set_visible(selected);
    }

    pub fn set_model(&self, model: &gtk::SingleSelection) {
        self.imp().signals.get().unwrap().set_target(Some(model));
    }
}
