// SPDX-License-Identifier: GPL-3.0-or-later
use gtk::{
    glib::{self, clone},
    prelude::*,
    subclass::prelude::*,
};

mod imp {
    use std::cell::RefCell;

    use super::*;

    #[derive(Debug, Default, gtk::CompositeTemplate, glib::Properties)]
    #[template(resource = "/com/belmoussaoui/Decoder/ui/text_page.ui")]
    #[properties(wrapper_type = super::TextPage)]
    pub struct TextPage {
        #[template_child]
        pub textview: TemplateChild<gtk::TextView>,
        #[template_child]
        pub child: TemplateChild<gtk::Widget>,

        #[property(get, set)]
        content: RefCell<String>,
    }

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

        fn class_init(klass: &mut Self::Class) {
            klass.set_layout_manager_type::<gtk::BinLayout>();
            klass.bind_template();
        }

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

    #[glib::derived_properties]
    impl ObjectImpl for TextPage {
        fn constructed(&self) {
            let obj = self.obj();
            obj.init_widgets();
            self.parent_constructed();
        }

        fn dispose(&self) {
            self.dispose_template();
        }
    }

    impl WidgetImpl for TextPage {}
}

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

impl TextPage {
    // Save the content of the TextBuffer into our content property
    // This allow us to bind the content property later & have everything updated
    // automagically
    fn refresh_content(&self) {
        let imp = self.imp();

        let buffer = imp.textview.buffer();
        let (start_iter, end_iter) = buffer.bounds();
        let text = buffer.text(&start_iter, &end_iter, true);

        self.set_content(text);
    }

    fn init_widgets(&self) {
        let imp = self.imp();
        imp.textview.buffer().connect_changed(clone!(
            #[weak(rename_to = page)]
            self,
            move |_buffer| {
                page.refresh_content();
            }
        ));
    }
}
