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

mod imp {
    use super::*;

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

    #[glib::object_subclass]
    impl ObjectSubclass for QRCodeUrl {
        const NAME: &'static str = "QRCodeUrl";
        type Type = super::QRCodeUrl;
        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 QRCodeUrl {}
    impl WidgetImpl for QRCodeUrl {}
    impl BoxImpl for QRCodeUrl {}
}

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

impl QRCodeUrl {
    pub fn new(url: url::Url) -> Self {
        let widget = glib::Object::new::<QRCodeUrl>();
        widget.init(url);
        widget
    }

    fn init(&self, url: url::Url) {
        let imp = self.imp();
        let escaped_url = glib::markup_escape_text(url.as_ref());

        imp.label
            .set_markup(&format!("<a href='{escaped_url}'>{escaped_url}</a>"));
    }
}
