/*
Copyright 2024, Savanni D'Gerinel <savanni@luminescent-dreams.com>

This file is part of FitnessTrax.

FitnessTrax is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

FitnessTrax is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License along with FitnessTrax. If not, see <https://www.gnu.org/licenses/>.
*/

use crate::{
    components::{DayDetail, DayEdit, Singleton, SingletonImpl},
    view_models::DayDetailViewModel,
};
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::cell::RefCell;

#[derive(Default)]
pub struct DayDetailViewPrivate {
    container: Singleton,
    view_model: RefCell<Option<DayDetailViewModel>>,
}

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

impl ObjectImpl for DayDetailViewPrivate {}
impl WidgetImpl for DayDetailViewPrivate {}
impl BoxImpl for DayDetailViewPrivate {}
impl SingletonImpl for DayDetailViewPrivate {}

glib::wrapper! {
    pub struct DayDetailView(ObjectSubclass<DayDetailViewPrivate>) @extends gtk::Box, gtk::Widget;
}

impl DayDetailView {
    pub fn new(view_model: DayDetailViewModel) -> Self {
        let s: Self = Object::builder().build();
        *s.imp().view_model.borrow_mut() = Some(view_model);

        s.append(&s.imp().container);

        s.view();

        s
    }

    fn view(&self) {
        let view_model = self.imp().view_model.borrow();
        let view_model = view_model
            .as_ref()
            .expect("DayDetailView has not been initialized with a view_model")
            .clone();

        self.imp().container.swap(&DayDetail::new(view_model, {
            let s = self.clone();
            move || s.edit()
        }));
    }

    fn edit(&self) {
        let view_model = self.imp().view_model.borrow();
        let view_model = view_model
            .as_ref()
            .expect("DayDetailView has not been initialized with a view_model")
            .clone();

        self.imp().container.swap(&DayEdit::new(view_model, {
            let s = self.clone();
            move || s.view()
        }));
    }
}
