import ObjectWrapper from 'src/utils/objectWrapper';
import {
  COLOR_LIGHT,
  COLOR_PRIMARY,
  COLOR_DARK,
  DefaultDepth,
  DragObjectDepth,
} from '../kanbans/Const';
import { EndlessCanvas, ItemType } from 'src/types/kanban_types';
import CreateRequestModal from '../kanbans/CreateRequestModal';
import { EventBus, Events } from 'src/boot/eventBus';

const CreateItem = (scene: EndlessCanvas, card: ObjectWrapper) => {
  let textInput = '';
  const icon = scene.add.image(0, 0, 'editicon').setDepth(1);
  icon.setInteractive({ cursor: 'pointer' });

  icon.on('pointerdown', () => {
    CreateRequestModal(
      scene,
      //@ts-ignore

      scene.store.getCurrentState.get(card.uuid).name,
      function (text) {
        console.log(`Content: '${text}'`);
        textInput = text;
      },
    )
      .setPosition(400, 300)
      .layout()
      .modalPromise({
        manualClose: true,
        duration: {
          in: 500,
          out: 500,
        },
      })
      .then(function (data) {
        //@ts-ignore
        if (data.text === 'Сохранить') {
          if (textInput) {
            const payload = {
              nomo: textInput,
              uuid: card.uuid,
              //@ts-ignore
              // kanvasoUuid: scene.store.getKanvaso[0].node.uuid,
            };
            //@ts-ignore
            scene.store.onEditKanvasoObjekto(payload);
          }
        }
      });
  });
  const item: ItemType = scene.rexUI.add.label({
    rtl: true,
    //@ts-ignore

    background: scene.rexUI.add.roundRectangle({
      radius: 10,
      color: COLOR_PRIMARY,
    }),
    text: scene.add.text(0, 0, card.name, {
      fontSize: 18,
    }),
    action: icon,
    actionSize: 24,
    align: 'left',
    space: {
      left: 5,
      right: 5,
      top: 5,
      bottom: 5,
      actionRight: 5,
    },
  });
  item.setData('uuid', card.uuid);

  //@ts-ignore
  item.payload = card.name;
  SetDraggable(item);

  EventBus.$on(Events.Change, (uuid, object) => {
    if (uuid === card.uuid) {
      //@ts-ignore
      item.setText(scene.store.getCurrentState.get(uuid)?.name);
    }
  });
  return item;
};

const SetDraggable = (item: ItemType): void => {
  item
    .setDraggable({
      sensor: item,
      target: item,
    })
    .on('sizer.dragstart', () => OnItemDragStart.call(item))
    .on('sizer.dragend', () => OnItemDragEnd.call(item));
};

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

const OnItemDragEnd = function (this): void {
  this.setDepth(DefaultDepth);
  this.getElement('background').setStrokeStyle();
  // console.log(this);
  // console.log(this.getParentSizer());
};

export default CreateItem;
