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

export default (listModule: ListModule) => {
  let temp = { x: 0, y: 0 };
  let tempDialogPos = { x: 0, y: 0 };

  return {
    row2parent(x: number, y: number, index: number) {
      temp.x = x - listModule.state.scrollOffset;
      temp.y = y;
      return temp;
    },
    col2Speed(x: number, y: number, speed: number) {
      temp.x = x;
      temp.y = y + speed;
      return temp;
    },
    parent2Row(x: number, y: number, index: number) {
      const row = Math.floor(index / listModule.state.rowCount);
      const factor = 1;
      temp.x = x + factor * listModule.state.scrollOffset;
      temp.y = y;
      return temp;
    },

    updateItem() {
      const dialogs = listModule.state.dialogs;
      const items = listModule.state.items;
      const actions = listModule.actions;

      let n = dialogs.length;

      let k = items.length;

      const systolic = 400;
      while (k--) {
        const item = items[k];
        const pos = actions.row2parent(item.x, item.y, k);
        item.offsetX = 0;
        item.offsetY = 0;
        item.currX = pos.x;
        item.currY = pos.y;
      }

      while (n--) {
        let k = items.length;
        const d = dialogs[n];
        if (!d.show) continue;

        //tempDialogPos = actions.row2parent(d.x,  d.y, d.itemIndex);

        while (k--) {
          //更新坐标
          const img = items[k];

          const dtaX = img.currX - d.x;
          let dtaY = img.currY - d.y;
          if (Math.abs(dtaX) < 1 && Math.abs(dtaY) < 1) {
            dtaY = -1;
          }
          const s = (d.height + img.w - systolic) * 0.5;
          const len = dtaX * dtaX + dtaY * dtaY;

          if (len > s * s) {
            continue;
          }

          const unit = 1.0 / Math.sqrt(len);
          img.currX = d.x + unit * dtaX * s;
          img.currY = d.y + unit * dtaY * s;

          const pos = actions.parent2Row(img.currX, img.currY, k);
          img.offsetX = pos.x - img.x;
          img.offsetY = pos.y - img.y;
        }
      }
    },
  };
};
