// SPDX-License-Identifier: GPL-3.0-or-later

//! A scrollable container.

use std::rc::Rc;

use glib::Cast;
use grx_macros::{gtk_component, props};
use gtk::glib;
use gtk::traits::BoxExt;

use crate::new_gc;

use super::gtk_props::apply;

#[props]
#[derive(Default, Debug)]
pub struct Props {}

pub fn scroll(mut props: Props) -> Rc<Scroll> {
    let scroll = gtk::ScrolledWindow::builder().build();
    for c in &props.children {
        let inner = c.clone().inner();
        let w: &gtk::Widget = inner.downcast_ref().unwrap();
        scroll.set_child(Some(w));
    }
    let widget: gtk::Widget = scroll.upcast();
    let comp = new_gc!(Scroll { widget, props });
    apply(comp.clone());
    comp
}

#[gtk_component(gtk::Widget)]
#[derive(Debug)]
pub struct Scroll {}

impl Scroll {
    pub fn push(&self, child: crate::Component) {
        if let Some(b) = self.widget.dynamic_cast_ref::<gtk::Box>() {
            let inner = child.inner();
            let w: &gtk::Widget = inner.downcast_ref().unwrap();
            b.append(w);
        }
    }
    pub fn remove(&self, child: crate::Component) {
        if let Some(b) = self.widget.dynamic_cast_ref::<gtk::Box>() {
            let inner = child.inner();
            let w: &gtk::Widget = inner.downcast_ref().unwrap();
            b.remove(w);
        }
    }
}
