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

use crate::qrcode_kind::Mail;

mod imp {
    use super::*;

    #[derive(Default, gtk::CompositeTemplate)]
    #[template(resource = "/com/belmoussaoui/Decoder/ui/qrcode_kind_mail.ui")]
    pub struct QRCodeMail {
        #[template_child]
        pub to_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub subject_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub body_label: TemplateChild<gtk::Label>,
    }

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

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

impl QRCodeMail {
    pub fn new(mail: Mail) -> Self {
        let widget = glib::Object::new::<QRCodeMail>();
        widget.init(mail);
        widget
    }

    fn init(&self, mail: Mail) {
        let imp = self.imp();
        let escaped_mailto = glib::markup_escape_text(&(Into::<String>::into(mail.clone())));
        let escaped_mail_to = glib::markup_escape_text(&mail.to);

        imp.to_label
            .set_markup(&format!("<a href='{escaped_mailto}'>{escaped_mail_to}</a>"));
        if let Some(ref subject) = mail.subject {
            imp.subject_label.set_label(subject);
        } else {
            imp.subject_label.set_visible(false);
        }

        if let Some(ref body) = mail.body {
            imp.body_label.set_label(body);
        } else {
            imp.body_label.set_visible(false);
        }
    }
}
