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

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;
  //@ts-ignore

  itemsBox.addBackground(scene.rexUI.add.roundRectangle({}), 'background');
  const itemBoxMap = new Map();
  if (cards.length) {
    cards.forEach((card) => {
      const item = CreateItem(scene, card);
      itemBoxMap.set(card.uuid, item);
      parentUuid = card.parentUuid;
      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) {
      const item = CreateItem(scene, object);
      itemBoxMap.set(object.uuid, item);

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

  return box.itemsBox;
};

export default CreateItemsBox;
