use crate::{
    components::{Date, Events, TransitCard, TransitClock},
    types::State,
};
use adw::prelude::AdwApplicationWindowExt;
use gio::resources_lookup_data;
use gtk::{prelude::*, STYLE_PROVIDER_PRIORITY_USER};

#[derive(Clone)]
pub struct ApplicationWindow {
    pub window: adw::ApplicationWindow,
    pub date_label: Date,
    pub events: Events,
    pub transit_card: TransitCard,
    pub transit_clock: TransitClock,
}

impl ApplicationWindow {
    pub fn new(app: &adw::Application) -> Self {
        let window = adw::ApplicationWindow::new(app);

        let stylesheet = String::from_utf8(
            resources_lookup_data(
                "/com/luminescent-dreams/dashboard/style.css",
                gio::ResourceLookupFlags::NONE,
            )
            .expect("stylesheet should just be available")
            .to_vec(),
        )
        .expect("to parse stylesheet");

        let provider = gtk::CssProvider::new();
        provider.load_from_data(&stylesheet);
        let context = window.style_context();
        context.add_provider(&provider, STYLE_PROVIDER_PRIORITY_USER);

        let layout = gtk::Box::builder()
            .orientation(gtk::Orientation::Vertical)
            .hexpand(true)
            .vexpand(true)
            .build();

        let date_label = Date::default();
        layout.append(&date_label);

        let events = Events::default();
        layout.append(&events);

        let transit_card = TransitCard::default();
        layout.append(&transit_card);

        let transit_clock = TransitClock::default();
        layout.append(&transit_clock);

        window.set_content(Some(&layout));

        Self {
            window,
            date_label,
            events,
            transit_card,
            transit_clock,
        }
    }

    pub fn update_state(&self, state: State) {
        self.date_label.update_date(state.date);
        self.events.set_events(state.events, state.next_event);
        if let Some(transit) = state.transit {
            self.transit_card.update_transit(&transit);
            self.transit_clock.update_transit(transit);
        }
    }
}
