use crate::elements::Element;
use crate::widget_factory::WidgetBuilder;
use gtk4::glib::{self, clone};
use gtk4::{Orientation, Widget, prelude::*};

impl WidgetBuilder {
    pub(super) fn create_box(&self, mut elements: Vec<Element>) -> Widget {
        let vbox = gtk4::Box::new(Orientation::Vertical, 2);
        elements.reverse();
        self.lazy_insert_element(&vbox, elements);
        vbox.upcast()
    }

    fn lazy_insert_element(&self, vbox: &gtk4::Box, mut elements: Vec<Element>) {
        glib::idle_add_local_once(clone!(
            #[weak]
            vbox,
            #[strong(rename_to = builder)]
            self,
            move || {
                let Some(element) = elements.pop() else {
                    return;
                };

                let widget = builder.build_element(element);
                vbox.append(&widget);

                builder.lazy_insert_element(&vbox, elements);
            }
        ));
    }
}
