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

use crate::qrcode_kind::Event;

mod imp {
    use super::*;

    #[derive(Default, gtk::CompositeTemplate)]
    #[template(resource = "/com/belmoussaoui/Decoder/ui/qrcode_kind_event.ui")]
    pub struct QRCodeEvent {
        #[template_child]
        pub summary_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub start_at_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub end_at_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub location_label: TemplateChild<gtk::Label>,
        #[template_child]
        pub description_label: TemplateChild<gtk::Label>,
    }

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

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

impl QRCodeEvent {
    pub fn new(event: Event) -> Self {
        let widget = glib::Object::new::<QRCodeEvent>();
        widget.init(event);
        widget
    }

    fn init(&self, event: Event) {
        let imp = self.imp();
        imp.summary_label.set_label(&event.summary);
        imp.start_at_label
            .set_label(&event.start_at.format("%Y-%m-%d").to_string());
        imp.end_at_label
            .set_label(&event.end_at.format("%Y-%m-%d").to_string());

        if let Some(ref description) = event.description {
            imp.description_label.set_label(description);
        } else {
            imp.description_label.set_visible(false);
        }

        if let Some(ref location) = event.location {
            imp.location_label.set_label(location);
        } else {
            imp.location_label.set_visible(false);
        }
    }
}
