<template>
  <v-arrow
    ref="arrow"
    :config="{
      points: [currentX, 0, currentX, 10],
      fill: currentColor,
      stroke: currentColor,
      strokeWidth: 1,
      pointerLength: 10,
      hitStrokeWidth: 10,
      pointerWidth: 10,
      ...currentMat,
    }"
  />
  <v-line
    :config="{
        points: [currentX, size!.height, currentX, 10],
        stroke: currentColor,
        strokeWidth: 2,
        listening: false,
        ...currentMat
      }"
  />
</template>

<script setup lang="ts">
import { computed, ref, watch, watchEffect } from "vue";
import {
  useDrag,
  useGlobalResize,
  useGlobalVar,
  useViewer,
  useViewerInvertTransformConfig,
  useViewerTransform,
} from "../drawing/hook";
import { Transform } from "konva/lib/Util";
import { Arrow } from "konva/lib/shapes/Arrow";
import { DC } from "../drawing/dec";

const props = withDefaults(defineProps<{ currentTime: number; follow?: boolean }>(), {
  follow: false,
});

const currentColor = "#fff";
const { misPixel } = useGlobalVar();
const emit = defineEmits<{ (e: "update:currentTime", num: number): void }>();

const arrow = ref<DC<Arrow>>();
const { drag } = useDrag(arrow);
watch(drag, (drag) => {
  if (!drag) return;
  const offsetX = drag.x;

  const currentX = props.currentTime * misPixel + offsetX;
  currentX >= 0 && emit("update:currentTime", currentX / misPixel);
});

const invConfig = useViewerInvertTransformConfig();
const currentX = computed(() => props.currentTime * misPixel);
const currentMat = computed(() => {
  return new Transform()
    .translate(currentX.value, 0)
    .scale(invConfig.value.scaleX, 1)
    .translate(-currentX.value, 0)
    .decompose();
});

const { viewer } = useViewer();
const { size } = useGlobalResize();
const viewerMat = useViewerTransform();
watch(
  () => {
    if (!props.follow || !size.value) return;
    return currentX.value;
  },
  (x) => {
    if (typeof x !== "number") return;
    const currentPixel = viewerMat.value.point({ x: currentX.value, y: 0 }).x;
    const offsetX = size.value!.width / 2 - currentPixel;
    viewer.movePixel({ x: offsetX, y: 0 });
  }
);
</script>
