use crate::CoreApi;
use adw::{prelude::*, subclass::prelude::*};
use glib::Object;
use otg_core::{ui::ConfigurationView, ChangeSettingRequest, CoreRequest};

#[derive(Default)]
pub struct ConfigurationPagePrivate {}

#[glib::object_subclass]
impl ObjectSubclass for ConfigurationPagePrivate {
    const NAME: &'static str = "Configuration";
    type Type = ConfigurationPage;
    type ParentType = adw::PreferencesPage;
}

impl ObjectImpl for ConfigurationPagePrivate {}
impl WidgetImpl for ConfigurationPagePrivate {}
impl PreferencesPageImpl for ConfigurationPagePrivate {}

glib::wrapper! {
    pub struct ConfigurationPage(ObjectSubclass<ConfigurationPagePrivate>)
        @extends adw::PreferencesPage, gtk::Widget,
        @implements gtk::Orientable;
}

impl ConfigurationPage {
    pub fn new(api: CoreApi, view: ConfigurationView) -> Self {
        let s: Self = Object::builder().build();

        let group = adw::PreferencesGroup::builder().build();

        let library_entry = &adw::EntryRow::builder()
            .name("library-path")
            .title(view.library.label)
            .show_apply_button(true)
            .build();
        if let Some(path) = view.library.value {
            library_entry.set_text(&path);
        }
        library_entry.connect_apply(move |entry| {
            api.dispatch(CoreRequest::ChangeSetting(
                ChangeSettingRequest::LibraryPath(entry.text().into()),
            ));
        });

        group.add(library_entry);

        s.add(&group);

        s
    }
}
