use adw::prelude::*;
use adw::subclass::prelude::*;
use gtk::{gio, glib};

use crate::widgets::KrFlatpakRow;

mod imp {
    use gtk::CompositeTemplate;

    use super::*;

    #[derive(Debug, Default, CompositeTemplate)]
    #[template(file = "flatpak_list.ui")]
    pub struct KrFlatpakList {
        #[template_child]
        pub list: TemplateChild<gtk::ListBox>,
        pub model: gtk::SortListModel,
    }

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

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

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

    impl ObjectImpl for KrFlatpakList {}

    impl WidgetImpl for KrFlatpakList {}

    impl PreferencesGroupImpl for KrFlatpakList {}
}

glib::wrapper! {
    pub struct KrFlatpakList(ObjectSubclass<imp::KrFlatpakList>)
        @extends adw::PreferencesGroup, gtk::Widget, gtk::Box;
}

impl KrFlatpakList {
    pub fn set_model(&self, model: Option<&impl IsA<gio::ListModel>>) {
        self.imp().list.bind_model(model, |x| {
            let flatpak = x.downcast_ref().unwrap();
            KrFlatpakRow::new(flatpak).upcast()
        });
    }
}
