import CreateItem from './CreateItem';
import ObjectWrapper from 'src/utils/objectWrapper';
import { ItemsBoxType } from 'src/types/kanban_types';
import { EventBus, Events } from 'src/boot/eventBus';
import AddDragDropItemBehavior from '../kanbans/AddDragDropItemBehavior';
import { EndlessCanvas } from '../spaces-2d/EndlessCanvas';
import { getAllChildrens } from '../utils/GetAllChildrens';

const CreateItemsBox = (
  scene: EndlessCanvas,
  cards: ObjectWrapper[],
  parentUuid: string,
) => {
  const itemsBox = scene.rexUI.add.sizer({
    orientation: 'y',
    space: {
      left: 5,
      right: 5,
      top: 5,
      bottom: 5,
      item: 5,
    },
  }) as undefined as ItemsBoxType;

  itemsBox.addBackground(
    //@ts-ignore
    scene.rexUI.add.roundRectangle({}),
    'background',
  );
  const itemBoxMap = new Map();
  cards.forEach((card) => {
    const item = CreateItem(scene, card);
    itemBoxMap.set(card.uuid, item);
    itemsBox.add(item, {
      proportion: 0,
      expand: true,
    });
  });

  const box = new AddDragDropItemBehavior(itemsBox);
  EventBus.$on(Events.Delete, (uuid, object) => {
    if (itemBoxMap.has(uuid)) {
      //@ts-ignore
      box.itemsBox.remove(itemBoxMap.get(uuid), true);
      box.itemsBox.getTopmostSizer().layout();
    }
  });

  EventBus.$on(Events.Create, (parentUuid1, object) => {
    if (parentUuid !== parentUuid1) {
      return;
    }
    const item = CreateItem(scene, object);

    scene.cameras.getCamera('ui').ignore(getAllChildrens(item));

    itemBoxMap.set(object.uuid, item);

    box.addItem(item);
    box.itemsBox.getTopmostSizer().layout();
  });

  return box.itemsBox;
};

export default CreateItemsBox;
