use crate::widgets::labled_switch::LabledSwitch;

use crate::ui::guessing::game::GuessingScene;
use crate::APP_ID;

use gio::Settings;
use glib::subclass::InitializingObject;
use gtk::glib::closure_local;
use gtk::subclass::prelude::*;
use gtk::{gio, glib, prelude::*, Button, CompositeTemplate};

#[derive(CompositeTemplate, Default)]
#[template(resource = "/org/foxarmy/learn-hieroglyph/guessing/setup/ui.xml")]
pub struct GuessingSetupScene {
    #[template_child]
    pub hiragana_enable: TemplateChild<LabledSwitch>,
    #[template_child]
    pub katakana_enable: TemplateChild<LabledSwitch>,
    #[template_child]
    pub ktr_enable: TemplateChild<LabledSwitch>,
    #[template_child]
    pub rtk_enable: TemplateChild<LabledSwitch>,
    #[template_child]
    pub start_button: TemplateChild<Button>,
    #[template_child]
    pub back_button: TemplateChild<Button>,
}

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

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

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

impl ObjectImpl for GuessingSetupScene {
    fn constructed(&self) {
        self.parent_constructed();

        let settings: Settings = Settings::new(APP_ID);

        let hiragana_enable_ref: &LabledSwitch = self.hiragana_enable.as_ref();
        let hiragana_enable_ref = hiragana_enable_ref.get_switch();
        settings
            .bind("is-hiragana-enabled", hiragana_enable_ref, "active")
            .build();

        let katakana_enable_ref: &LabledSwitch = self.katakana_enable.as_ref();
        let katakana_enable_ref = katakana_enable_ref.get_switch();
        settings
            .bind("is-katakana-enabled", katakana_enable_ref, "active")
            .build();

        let ktr_enable_ref: &LabledSwitch = self.ktr_enable.as_ref();
        let ktr_enable_ref = ktr_enable_ref.get_switch();
        settings
            .bind("is-ktr-enabled", ktr_enable_ref, "active")
            .build();

        let rtk_enable_ref: &LabledSwitch = self.rtk_enable.as_ref();
        let rtk_enable_ref = rtk_enable_ref.get_switch();
        settings
            .bind("is-rtk-enabled", rtk_enable_ref, "active")
            .build();

        let binding = self.obj();

        self.start_button.connect_closure("clicked", 
                                          false,
                                          closure_local!(@strong binding => move |_b: &Button| {
                                            let new_win: GuessingScene = GuessingScene::new(&binding.application().unwrap());
                                            new_win.present();
        }));
    }
}

impl WidgetImpl for GuessingSetupScene {}

impl WindowImpl for GuessingSetupScene {}

impl ApplicationWindowImpl for GuessingSetupScene {}
