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

use crate::qrcode_kind::Sms;

mod imp {
    use super::*;

    #[derive(Default, gtk::CompositeTemplate)]
    #[template(resource = "/com/belmoussaoui/Decoder/ui/qrcode_kind_sms.ui")]
    pub struct QRCodeSms {
        #[template_child]
        pub phone_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub content_label: TemplateChild<gtk::Label>,
    }

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

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

        fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
            obj.init_template();
        }
    }
    impl ObjectImpl for QRCodeSms {}
    impl WidgetImpl for QRCodeSms {}
    impl BoxImpl for QRCodeSms {}
}

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

impl QRCodeSms {
    pub fn new(sms: Sms) -> Self {
        let widget = glib::Object::new::<QRCodeSms>();
        widget.init(sms);
        widget
    }

    fn init(&self, sms: Sms) {
        let imp = self.imp();
        let escaped_phone = glib::markup_escape_text(&sms.phone);

        imp.phone_label.set_markup(&format!(
            "<a href='tel:{escaped_phone}'>{escaped_phone}</a>"
        ));
        imp.content_label.set_label(&sms.content);
    }
}
