import ListModule from "..";
import { Dialog, ShowItem } from "../state";

export default (listModule: ListModule) => {

  let lastDialogTime = Date.now();
  let lastDialogId = "";

  return {
    addDialog(e: any, index: number) {
      const item = listModule.state.items[index];

      listModule.actions.popDialog(e, item, index);
    },

    popDialog(e: any, item: ShowItem, index = 0) {
      if (listModule.state.dialogs.length >= 4) {
        return false;
      }
      if (Date.now() - lastDialogTime < 300 && lastDialogId == item.id) { 
         return;
      }
      lastDialogTime = Date.now();
      lastDialogId = item.id;
      
      const height = listModule.state.parentHeight;
      const width = listModule.state.parentWidth;
      let x = e.clientX;
      let y = e.clientY;
      const conNum = 800 / 4 + 120;
      if (x - conNum <= 0) {
        x = Math.round(x + (conNum - x));
      }
      if (x + conNum > width) {
        x = Math.round(x - (x + conNum - width));
      }
      if (y + conNum > height) {
        y = Math.round(y - (y + conNum - height));
      }
      const dialog = {
        id: Date.now(),
        show: true,
        width: 800,
        height: 800,
        x: x,
        y: y,
        dataId: item.id,
        itemIndex: index,
      };
      listModule.state.dialogs.push(dialog);
    },

    deleteDialog(dialg: Dialog) {
      const i = listModule.state.dialogs.indexOf(dialg);
      if (i != -1) {
        listModule.state.dialogs.splice(i, 1);
      }
    },
    closingDialog(dialg: Dialog) {
      // dialg.width = 0;
      // dialg.height = 0;
      dialg.show = false;
      // listModule.actions.updateItem();
    },
    moveDialog(dialgId: number, offx: number, offy: number) {
      const d = listModule.state.dialogs.find((item) => item.id == dialgId);
      if (!d) return;
      d.x = Math.round(offx + d.x);
      d.y = Math.round(offy + d.y);
      // listModule.actions.updateItem();
    },

    update() {},
  };
};
