import { CircleConfig } from "konva/lib/shapes/Circle";
import { themeMouseColors } from "@/constant/help-style.ts";
import {
  BaseItem,
  generateSnapInfos,
  getBaseItem,
  getRectSnapPoints,
} from "../util.ts";
import { getMouseColors } from "@/utils/colors.ts";
import { AddMessage } from "@/core/hook/use-draw.ts";
import { lineCenter, lineLen } from "@/utils/math.ts";
import { Transform } from "konva/lib/Util";

export { default as Component } from "./circle.vue";
export { default as TempComponent } from "./temp-circle.vue";

export const shapeName = "圆形";
export const defaultStyle = {
  dash: [30, 0],
  stroke: themeMouseColors.theme,
  strokeWidth: 1,
};

export const addMode = "area";

export const getMouseStyle = (data: CircleData) => {
  const fillStatus = data.fill && getMouseColors(data.fill);
  const strokeStatus = getMouseColors(data.stroke || defaultStyle.stroke);
  const strokeWidth = data.strokeWidth || defaultStyle.strokeWidth;
  return {
    default: { fill: fillStatus && fillStatus.pub, stroke: strokeStatus.pub, strokeWidth },
    hover: { fill: fillStatus && fillStatus.hover, stroke: strokeStatus.hover },
    press: { fill: fillStatus && fillStatus.press, stroke: strokeStatus.press },
  };
};

export const getSnapInfos = (data: CircleData) => {
  return generateSnapInfos(getSnapPoints(data), true, false);
};

export const getSnapPoints = (data: CircleData) => {
  const dec = new Transform(data.mat).decompose()
  const points = getRectSnapPoints(data.radiusX * 2, data.radiusY * 2).map((v) => ({
    x: v.x + dec.x,
    y: v.y + dec.y,
  }));
  // const size = data.radius * 2;
  return points
}

export type CircleData = Partial<typeof defaultStyle> &
  BaseItem & {
    opacity?: number,
    fill?: string
    mat: number[];
    radiusX: number
    radiusY: number
  };

export const dataToConfig = (data: CircleData): CircleConfig => ({
  ...defaultStyle,
  ...data,
});

export const interactiveToData = (
  info: AddMessage<'circle'>,
  preset: Partial<CircleData> = {}
): CircleData | undefined => {
  if (info.cur) {
    const item = {
      ...getBaseItem(),
      ...preset,
    } as unknown as CircleData;
    return interactiveFixData(item, info);
  }
};

export const interactiveFixData = (
  data: CircleData,
  info: AddMessage<'circle'>
) => {
  const area = info.cur!;
  const sx = Math.abs((area[1].x - area[0].x)) / 2
  const sy = Math.abs((area[1].y - area[0].y)) / 2
  const center = lineCenter(area)

  data.mat = new Transform().translate(center.x, center.y).m
  data.radiusX = sx
  data.radiusY = sy
  return data;
};
