import { ObjectWrapper, TreeNode } from 'src/types/stores/kanvaso';
import { COLOR_LIGHT, COLOR_PRIMARY, COLOR_DARK } from './Const';
import { DefaultDepth, DragObjectDepth } from './Const';
import CreateItemsBox from '../cards/CreateItemsBox';
import { EndlessCanvas } from 'src/types/kanban_types';

const CreateColumnPanel = (
  scene: EndlessCanvas,
  column: ObjectWrapper,
  registry: Phaser.Data.DataManager,
) => {
  const panel = scene.rexUI.add
    .dialog({
      width: 120,
      space: { left: 10, right: 10, top: 10, bottom: 10 },
      //@ts-ignore

      background: scene.rexUI.add.roundRectangle({
        strokeColor: COLOR_DARK,
        radius: 0,
      }),
      title: CreateTitle(scene, column, registry),
      content: CreateItemsBox(
        scene,
        column.childrens ? column.childrens : [],
        registry,
      ),
      proportion: {
        content: 1,
      },
    })
    .setOrigin(0, 0);

  SetDraggable(panel);

  return panel;
};

const CreateTitle = (
  scene: EndlessCanvas,
  column: ObjectWrapper,
  registry: Phaser.Data.DataManager,
) => {
  const title = scene.rexUI.add.label({
    //@ts-ignore

    background: scene.rexUI.add.roundRectangle({
      color: COLOR_LIGHT,
    }),
    text: scene.add.text(0, 0, column.name || '', {
      fontSize: 18,
    }),
    align: 'left',
    space: {
      left: 5,
      right: 5,
      top: 5,
      bottom: 5,
    },
  });

  registry.events.on('changedata', (parent, key, data, previousData) => {
    if (data.uuid === column.uuid) {
      title.setText(data.name);
    }
  });

  return title;
};

const SetDraggable = (panel: any) => {
  panel
    .setDraggable({
      sensor: 'title',
      target: panel,
    })
    .on('sizer.dragstart', OnPanelDragStart, panel)
    .on('sizer.dragend', OnPanelDragEnd, panel);
};

const OnPanelDragStart = function (this: any) {
  this.setDepth(DragObjectDepth);
  this.getElement('background').setStrokeStyle(3, 0xff0000);
};

const OnPanelDragEnd = function (this: any) {
  this.setDepth(DefaultDepth);
  this.getElement('background').setStrokeStyle(2, COLOR_DARK);
};

export default CreateColumnPanel;
