import mitt from "mitt";
import { text, table, compass, title, bgImage } from "./shape";
import Layer from "./editCAD/Layer";
import { history } from "./editCAD/History/History.js";
import { uploadFile } from "@/store/system";

// const toStore = (refs) => {
//   return {
//     bgImage: refs.baseMap?.data || null,
//     shapes: refs.shapes.map(shape => shape.data)
//   }
// }

export const create = async (store, canvas) => {
  const refs = {
    ctx: canvas.getContext("2d"),
    bus: mitt(),
    shapes: [],
    baseMap: null,
  };

  const layer = new Layer();
  await layer.start(canvas, store);
  layer.uiControl.bus.on("showAttribute", ({ type, value: data }) => {
    const shape = {
      data: { type },
      delete: () => {
        layer.uiControl.clearUI();
        layer.uiControl.setAttributes(type, "delete");
      },
    };
    const update = (newData) => {
      layer.uiControl.setAttributes(type, "update", newData);
    };
    switch (type) {
      case table: {
        data = data || [
          { width: 160, height: 60, value: "", colIndex: 0, rowIndex: 0 },
          { width: 160, height: 60, value: "", colIndex: 1, rowIndex: 0 },
        ];
        shape.data.content = data;
        shape.setContent = (newData) => {
          shape.data.content = newData;
          update(newData);
        };
        break;
      }
      case title:
      case text: {
        console.log(data);
        data = data || "";
        shape.data.text = data;
        shape.setText = (newData) => {
          shape.data.text = newData;
          update(newData);
        };
        break;
      }
      case compass: {
        data = data || 0;
        console.log(data);
        shape.data.rotate = data;
        shape.setRotate = (newData) => {
          shape.data.rotate = newData;
          update(newData);
        };
      }
    }
    refs.bus.emit("selectShape", shape);
  });
  layer.uiControl.bus.on("hideAttribute", () => {
    refs.bus.emit("selectShape", null);
  });
  history.bus.on("undoAvailable", (availabe) => {
    console.log("0.0.0.0", !availabe);
    refs.bus.emit("backDisabled", !availabe);
  });
  history.bus.on("redoAvailable", (availabe) =>
    refs.bus.emit("forwardDisabled", !availabe)
  );

  setTimeout(() => {
    // layer.uiControl.bus.emit('showAttribute', { type: compass, data: 0 })
    // history.bus.emit('undoAvailable', true)
    // history.bus.emit('redoAvailable', true)
  }, 100);

  const board = {
    bus: refs.bus,
    el: canvas,
    async getStore() {
      const data = layer.uiControl.exportJSON();
      const floor = data.floors[0];
      const shapes = [];

      if (floor) {
        const bgImage = floor.image.src;
        if (bgImage && bgImage.includes("blob:")) {
          const url = await fetch(bgImage)
            .then((res) => res.blob())
            .then((blob) =>
              uploadFile(new File([blob], (store.id || "image") + ".png"))
            );

          floor.image.src = url;
          console.log(url);
        }
        shapes.push({ type: title, text: floor.title.value });
      }
      return {
        id: store.id,
        shapes,
        ...layer.uiControl.exportJSON(),
      };
    },
    viewInit() {
      layer.uiControl.menu_flex();
    },
    unSelectShape() {
      layer.uiControl.clearUI();
    },
    setDefaultTable(rbTable, rtTable) {
      if (rbTable) {
        layer.uiControl.initDownTable(rbTable);
      }
      if (rtTable) {
        layer.uiControl.initTopTable(rtTable);
      }
    },
    initHistory() {
      history.init();
    },
    readyAddShape(shapeType, onFine) {
      layer.uiControl.selectUI = shapeType;
      layer.uiControl.updateEventNameForSelectUI();
      const finePack = () => {
        layer.uiControl.bus.off("hideUI", finePack);
        onFine();
      };
      layer.uiControl.bus.on("hideUI", finePack);
    },
    back() {
      history.handleUndo();
    },
    forward() {
      history.handleRedo();
    },
    setImage(url) {
      layer.uiControl.setAttributes(bgImage, "update", url);
    },
    export() {
      const $canvas = document.createElement("canvas");
      $canvas.width = canvas.width;
      $canvas.height = canvas.height;

      const cctx = $canvas.getContext("2d");
      cctx.rect(0, 0, $canvas.width, $canvas.height);
      cctx.fillStyle = "#fff";
      cctx.fill();
      cctx.drawImage(canvas, 0, 0, $canvas.width, $canvas.height);

      return new Promise((resolve) => {
        // resolve(layer.uiControl.menu_screenShot())
        $canvas.toBlob(resolve, "image/jpeg", 1);
      });
    },
    calcTableShape(data) {
      return new Promise((resolve) => {
        const tableData = {
          data: {
            type: table,
            content: data
              .map((cols, index) => [
                {
                  rowIndex: index,
                  colIndex: 0,
                  width: 0,
                  height: 0,
                  value: cols[0],
                },
                {
                  rowIndex: index,
                  colIndex: 1,
                  width: 0,
                  height: 0,
                  value: cols[1],
                },
              ])
              .flat(),
          },
          setContent(newData) {
            board.bus.emit("selectShape", null);
            resolve({ type: table, content: newData });
          },
          autoSet: true,
        };
        board.bus.emit("selectShape", tableData);
      });
    },
    destroy() {},
  };

  return board;
};

export * from "./shape";

export default create;

export { shapes } from "./shapes";
