import { DC, EntityShape } from "@/deconstruction";
import { Ref } from "vue";
import { useStage } from "./use-global-vars";
import { useViewerInvertTransform } from "./use-viewer";
import { Transform } from "konva/lib/Util";


export const useGetShapeCopyTransform = (shape: Ref<DC<EntityShape> | undefined>, padding = 10) => {
  const stage = useStage()
  const invViewTransform = useViewerInvertTransform()

  return () => {
    const $shape = shape.value!.getNode()
    const $stage = stage.value!.getNode()
    const shapeRect = $shape.getClientRect({ skipTransform: false })
    const stageRect = {
      x: 0,
      y: 0,
      width: $stage.width(),
      height: $stage.height()
    }
    // 可用性，分别对应 右左上下
    const available = [
      {
        diff: stageRect.x + stageRect.width - (shapeRect.x + shapeRect.width * 2 + padding),
        translate:  { x: shapeRect.width + padding, y: 0 },
      },
      {
        diff: shapeRect.x - shapeRect.width - padding - stageRect.x,
        translate:  { x: -shapeRect.width - padding, y: 0 },
      },
      {
        diff: shapeRect.y - shapeRect.height - padding - stageRect.y,
        translate:  { x: 0, y: -shapeRect.height - padding },
      },
      {
        diff: stageRect.y + stageRect.height - (shapeRect.y + shapeRect.height * 2 + padding),
        translate:  { x: 0, y: shapeRect.height + padding },
      }
    ]
    let translate = available.find(({ diff }) => diff >= 0)?.translate
    if (!translate) {
      // 都不可用取最可用复制位置  
      let maxDiff = available[0].diff
      let ndx = 0
      for (let i = 1; i < available.length; i++) {
        if (available[i].diff > maxDiff) {
          ndx = i
        }
      }
      translate = available[ndx].translate
    }

    const origin = invViewTransform.value.point({x: 0, y: 0})
    const target = invViewTransform.value.point(translate);
    // 转化为真实坐标
    console.log(target.x - origin.x, target.y - origin.y)
    return  new Transform().translate(target.x - origin.x, target.y - origin.y)
  }
}