use crate::{components::Label, soluna_client::SunMoon};
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};

pub struct TransitCardPrivate {
    sunrise: Label,
    sunset: Label,
    moonrise: Label,
    moonset: Label,
}

impl Default for TransitCardPrivate {
    fn default() -> Self {
        Self {
            sunrise: Label::new(None, Some(gio::ThemedIcon::new("daytime-sunrise-symbolic"))),
            sunset: Label::new(None, Some(gio::ThemedIcon::new("daytime-sunset-symbolic"))),
            moonrise: Label::new(None, Some(gio::ThemedIcon::new("moon-outline-symbolic"))),
            moonset: Label::new(None, Some(gio::ThemedIcon::new("moon-outline-symbolic"))),
        }
    }
}

#[glib::object_subclass]
impl ObjectSubclass for TransitCardPrivate {
    const NAME: &'static str = "TransitCard";
    type Type = TransitCard;
    type ParentType = gtk::Grid;
}

impl ObjectImpl for TransitCardPrivate {}
impl WidgetImpl for TransitCardPrivate {}
impl GridImpl for TransitCardPrivate {}

glib::wrapper! {
    pub struct TransitCard(ObjectSubclass<TransitCardPrivate>) @extends gtk::Grid, gtk::Widget;
}

impl Default for TransitCard {
    fn default() -> Self {
        let s: Self = Object::builder().build();
        s.add_css_class("card");
        s.set_column_homogeneous(true);

        s.attach(&s.imp().sunrise, 0, 0, 1, 1);
        s.attach(&s.imp().sunset, 0, 1, 1, 1);
        s.attach(&s.imp().moonrise, 1, 0, 1, 1);
        s.attach(&s.imp().moonset, 1, 1, 1, 1);

        s
    }
}

impl TransitCard {
    pub fn update_transit(&self, transit_info: &SunMoon) {
        self.imp()
            .sunrise
            .set_text(format!("{}", transit_info.sunrise.format("%H:%M")).as_ref());
        self.imp()
            .sunset
            .set_text(format!("{}", transit_info.sunset.format("%H:%M")).as_ref());
        self.imp().moonrise.set_text(
            &transit_info
                .moonrise
                .map(|time| format!("{}", time.format("%H:%M")))
                .unwrap_or("".to_owned()),
        );
        self.imp().moonset.set_text(
            &transit_info
                .moonset
                .map(|time| format!("{}", time.format("%H:%M")))
                .unwrap_or("".to_owned()),
        );
    }
}
