mod imp;

use std::ops::Deref;

use glib::Object;
use gtk::{gio::{self, prelude::*}, glib::{self, subclass::types::ObjectSubclassIsExt}, Application, Button};
use gtk::gio::Settings;
use rand::Rng;
use crate::{game::*, APP_ID};

glib::wrapper! {
    pub struct GuessingScene(ObjectSubclass<imp::GuessingScene>)
        @extends gtk::ApplicationWindow, gtk::Window, gtk::Widget,
        @implements gio::ActionGroup, gio::ActionMap, gtk::Accessible, gtk::Buildable,
                    gtk::ConstraintTarget, gtk::Native, gtk::Root, gtk::ShortcutManager;
}

impl GuessingScene {
    pub fn new(app: &Application) -> Self {
        Object::builder().property("application", app).build()
    }

    pub fn get_back_button(&self) -> &Button {
        self.imp().back_button.as_ref()
    }

    pub fn read_settings(&self) {
        let settings = Settings::new(APP_ID);

        *self.imp().ktr.borrow_mut() = settings.boolean("is-ktr-enabled");
        *self.imp().rtk.borrow_mut() = settings.boolean("is-rtk-enabled");
        *self.imp().hiragana.borrow_mut() = settings.boolean("is-hiragana-enabled");
        *self.imp().katakana.borrow_mut() = settings.boolean("is-katakana-enabled");
    }

    pub fn init(&self) {
        self.read_settings();

        let ktr = *self.imp().ktr.borrow();
        let rtk = *self.imp().rtk.borrow();
        let hiragana = *self.imp().hiragana.borrow();
        let katakana = *self.imp().katakana.borrow();

        *self.imp().question.borrow_mut() = ask(ktr, rtk, hiragana, katakana);
        *self.imp().exact_kana.borrow_mut() = if hiragana && katakana {
            if rand::thread_rng().gen_bool(0.5) {
                Kanas::Hiragana
            } else {
                Kanas::Katakana
            }
        } else if hiragana {
            Kanas::Hiragana
        } else {
            Kanas::Katakana
        };

        *self.imp().correct_answer.borrow_mut() = get_kana_pair_for_hieroglyph(
            match self.imp().question.borrow().get_kana() {
                Kanas::Romaji => match self.imp().exact_kana.borrow().deref() {
                    Kanas::Hiragana => &Kanas::Hiragana,
                    Kanas::Katakana => &Kanas::Katakana,
                    _ => panic!("HOW DID YOU GET HERE?!"),
                },
                _ => &Kanas::Romaji,
            },
            &self.imp().question.borrow(),
        );

        let binding = generate_question_text(&self.imp().question.borrow(), self.imp().exact_kana.borrow().deref());
        let text: &str = &(binding.as_str());
        self.imp().question_label.set_label(text);

    }
}
