import { PanelsBoxType } from 'src/types/kanban_types';
import Phaser from 'phaser';

class AddDragDropColumnPanelBehavior {
  panelsBox: PanelsBoxType;

  constructor(panelsBox: PanelsBoxType) {
    this.panelsBox = panelsBox;
    this.addDragDropBehavior();
  }

  private addDragDropBehavior(): void {
    const panels = this.panelsBox.getElement('items');
    panels.forEach((panel) => this.addPanelBehavior(panel));
  }

  private addPanelBehavior(panel: any): void {
    panel
      .on('sizer.dragstart', () => {
        console.log(panel.children[1].children[0].children[1].text);
        this.panelsBox.remove(panel);
        panel.layout();
      })
      .on('sizer.dragend', (pointer: Phaser.Input.Pointer) => {
        this.panelsBox.insertAtPosition(pointer.x, pointer.y, panel, {
          expand: true,
        });
        this.arrangePanels();
      });
  }

  private arrangePanels(): void {
    const panels = this.panelsBox.getElement('items');

    for (const panel of panels) {
      panel.setData({ startX: panel.x, startY: panel.y });
    }

    this.panelsBox.getTopmostSizer().layout();

    for (const panel of panels) {
      const fromX = panel.getData('startX') as number;
      const fromY = panel.getData('startY') as number;
      if (panel.x !== fromX || panel.y !== fromY) {
        panel.moveFrom({ x: fromX, y: fromY, speed: 300 });
      }
    }
  }

  public addPanel(panel: any): void {
    this.panelsBox.add(panel, { proportion: 0, expand: true });
    this.addPanelBehavior(panel);
  }
}

export default AddDragDropColumnPanelBehavior;
