import { Polygons } from "./polygons";
import { Manage } from "../openlayer";
import { register, BoundQueryPlugin } from "drawing-board";
import { PolygonsAttrib, PolygonsPointAttrib, Scene } from "@/request/type";
import { SceneStatus } from "@/store/scene";

const initBoard = register({ polygons: Polygons }, { bound: new BoundQueryPlugin() });

export const scenePosTransform = (scenes: Scene[]) => {
  const points: PolygonsPointAttrib[] = [];

  scenes.forEach((scene) => {
    if (scene.calcStatus !== SceneStatus.SUCCESS) {
      return;
    }
    scene.scenePos.forEach((pos) => {
      if (!pos.pos || pos.pos.length === 0) {
        return;
      }
      points.push({
        x: pos.pos[0],
        y: pos.pos[1],
        title: pos.name,
        id: pos.id.toString(),
        rtk: true,
      });
    });
  });
  return points;
};

export const createBoard = (container: HTMLDivElement, mapManage: Manage) => {
  const board = initBoard(container, { polygons: undefined }, false);
  const syncBound = () => {
    const bound = mapManage.getBound();
    board.bound.setSize(container.offsetWidth, container.offsetHeight);
    board.bound.setBound([bound[0], bound[3], bound[2], bound[1]]);
  };

  const { map } = mapManage;
  map.addEventListener("moveend", syncBound);

  board.bound.enableMove((newBound) => {
    mapManage.setBound(newBound);
    return true;
  });
  board.bound.enableWheel((newBound) => {
    mapManage.setBound(newBound);
    return true;
  });

  return {
    getData() {
      return board.getData().polygons;
    },
    setData(polygons: PolygonsAttrib, id: string) {
      board.setData({ polygons: { ...polygons, id } });
    },
    destory() {
      board.destory();
      map.removeEventListener("moveend", syncBound);
    },
    polygon() {
      return board.tree.children[0] as Polygons;
    },
    getPixelFromCoordinate(point: number[]) {
      return board.tree.getPixelFromStage(point);
    },
  };
};
