use glib::{Properties, prelude::*, subclass};
use gtk4::{
    Accessible, Actionable, Buildable, CompositeTemplate, ConstraintTarget, ListBoxRow, Widget, subclass::prelude::*,
};
use once_cell::sync::Lazy;
use std::cell::RefCell;

mod imp {
    use glib::subclass::Signal;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate, Properties)]
    #[properties(wrapper_type = super::ShareRow)]
    #[template(file = "data/resources/ui_templates/share/row.blp")]
    pub struct ShareRow {
        #[property(get, set, nullable)]
        pub name: RefCell<Option<String>>,

        #[property(get, set, name = "icon-name", nullable)]
        pub icon_name: RefCell<Option<String>>,

        #[property(get, set, name = "url-template", nullable)]
        pub url_template: RefCell<Option<String>>,
    }

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

        fn class_init(klass: &mut Self::Class) {
            klass.bind_template();
            klass.bind_template_callbacks();
        }

        fn instance_init(obj: &subclass::InitializingObject<Self>) {
            obj.init_template();
        }
    }

    #[glib::derived_properties]
    impl ObjectImpl for ShareRow {
        fn signals() -> &'static [Signal] {
            static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
                vec![
                    Signal::builder("share")
                        .param_types([super::ShareRow::static_type()])
                        .build(),
                ]
            });
            SIGNALS.as_ref()
        }
    }

    impl WidgetImpl for ShareRow {}

    impl ListBoxRowImpl for ShareRow {}

    #[gtk4::template_callbacks]
    impl ShareRow {
        #[template_callback]
        fn on_clicked(&self) {
            self.obj().emit_by_name::<()>("share", &[&*self.obj()])
        }
    }
}

glib::wrapper! {
    pub struct ShareRow(ObjectSubclass<imp::ShareRow>)
        @extends Widget, ListBoxRow,
        @implements Accessible, Actionable, Buildable, ConstraintTarget;
}

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