use crate::{
    components::render_panel::messages::{MonitorInputMsg, MonitorOutputMsg},
    render::{Layer, Render},
};

use super::{render::render::RenderModel, sidebar::{sidebar::SideBarModel, SideBarOutputMsg}};
use adw::prelude::*;
use relm4::*;
pub struct MonitorModel {
    sidebar_open: bool,
    sidebar_width: i32,
    layers: Vec<Layer>,
    sidebar: Controller<SideBarModel>,
}

pub struct MonitorWidgets {
    paned: gtk::Paned,
}

#[relm4::component(pub)]
impl SimpleComponent for MonitorModel {
    type Init = ();
    type Output = MonitorOutputMsg;
    type Input = MonitorInputMsg;

    view! {
        adw::BreakpointBin {
            set_hexpand: true,
            set_vexpand: true,
            set_height_request: 500,
            set_width_request: 700,
            #[wrap(Some)]
            set_child=&gtk::Paned{
                set_position: 1000,
                #[wrap(Some)]
                #[name="render"]
                set_start_child=&Render{
                    #[watch]
                    set_interior_layers: model.layers.clone(),
                },
                #[wrap(Some)]
                set_end_child=model.sidebar.widget(),
            }
        }
    }

    fn init(
        init: Self::Init,
        root: &Self::Root,
        sender: relm4::ComponentSender<Self>,
    ) -> relm4::ComponentParts<Self> {
        let sidebar: Controller<SideBarModel> = SideBarModel::builder()
            .launch(())
            .forward(sender.input_sender(), |msg| match msg {
                SideBarOutputMsg::NewLayer(layer) => MonitorInputMsg::AddLayer(layer),
            });
        let model = MonitorModel {
            sidebar_open: true,
            sidebar_width: 400,
            layers: vec![],
            sidebar,
        };

        let widgets = view_output! {};
        ComponentParts { model, widgets }
    }

    fn update(&mut self, msg: Self::Input, _sender: ComponentSender<Self>) {
        match msg {
            MonitorInputMsg::AddLayer(layer) => {
                self.layers.push(layer);
                _sender
                    .output_sender()
                    .send(MonitorOutputMsg::LayerAdded(0))
                    .unwrap();
            }
            MonitorInputMsg::RemoveLayer(index) => {
                self.layers.remove(index);
                _sender
                    .output_sender()
                    .send(MonitorOutputMsg::LayerRemoved(0))
                    .unwrap();
            }
            MonitorInputMsg::UpdateLayer((idx, f)) => {
                f(&mut self.layers[idx]);
                _sender
                    .output_sender()
                    .send(MonitorOutputMsg::LayerUpdated(0))
                    .unwrap();
            }
            MonitorInputMsg::None => {}
        }
    }

}
