use crate::ecs::ui::builder::UiTreeBuilder;
use crate::ecs::ui::components::*;

use crate::prelude::*;
pub struct TileBuilder<'t, 'a> {
    pub(super) tree: &'t mut UiTreeBuilder<'a>,
    pub(super) container: freecs::Entity,
}

impl<'t, 'a> TileBuilder<'t, 'a> {
    pub fn add_text(&mut self, text: impl Into<String>) -> usize {
        self.tree.world_mut().resources.text.cache.add_text(text)
    }

    pub fn pane(&mut self, title: &str) -> Option<(TileId, freecs::Entity)> {
        ui_tile_add_pane(self.tree.world_mut(), self.container, title)
    }

    pub fn pane_sibling(
        &mut self,
        sibling: TileId,
        title: &str,
    ) -> Option<(TileId, freecs::Entity)> {
        let tabs_id = match self
            .tree
            .world_mut()
            .ui
            .get_ui_tile_container(self.container)
        {
            Some(data) => data.find_parent_tabs(sibling)?,
            None => return None,
        };
        ui_tile_add_pane_to(self.tree.world_mut(), self.container, tabs_id, title)
    }

    pub fn split_from(
        &mut self,
        pane: TileId,
        direction: SplitDirection,
        ratio: f32,
        title: &str,
    ) -> Option<(TileId, freecs::Entity)> {
        let target = match self
            .tree
            .world_mut()
            .ui
            .get_ui_tile_container(self.container)
        {
            Some(data) => data.find_parent_tabs(pane).unwrap_or(data.root),
            None => return None,
        };
        ui_tile_split(
            self.tree.world_mut(),
            self.container,
            target,
            direction,
            ratio,
            title,
        )
    }

    pub fn content(
        &mut self,
        content_entity: freecs::Entity,
        f: impl FnOnce(&mut UiTreeBuilder<'a>),
    ) {
        self.tree.push_parent(content_entity);
        f(self.tree);
        self.tree.pop_parent();
    }
}
