import { Vector3, world } from "@minecraft/server";
import { Vector3ToCommandString } from "../utils/vectorUtils";
import { delay } from "../utils/waitUtil";

let animationPlaying = false;

function setAmimationPlaying(value: boolean) {
  animationPlaying = value;
}
function getAnimationPlaying() {
  return animationPlaying;
}

class ClonePos {
  point1: Vector3;
  point2: Vector3;

  constructor(point1: Vector3, point2: Vector3) {
    this.point1 = point1;
    this.point2 = point2;
  }
}

async function SetFrame(frame: ClonePos, destination: Vector3) {
  await world
    .getDimension("overworld")
    .runCommandAsync(
      `/clone ${Vector3ToCommandString(frame.point1)} ${Vector3ToCommandString(frame.point2)} ${Vector3ToCommandString(
        destination
      )}`
    );
}

async function playAnimation(
  frames: ClonePos[],
  delayTime: number,
  reverse: boolean,
  destination: Vector3,
  force: boolean = false
) {
  if (animationPlaying && !force) {
    world.sendMessage("Animation already playing");
    return;
  }
  let frameCount = frames.length;
  if (!force) {
    animationPlaying = true;
  }

  for (let i = 0; i < frameCount; i++) {
    let frame = reverse ? frames[frameCount - i - 1] : frames[i];
    await world
      .getDimension("overworld")
      .runCommandAsync(
        `/clone ${Vector3ToCommandString(frame.point1)} ${Vector3ToCommandString(
          frame.point2
        )} ${Vector3ToCommandString(destination)}`
      );
    await delay(delayTime);
  }
  if (!force) {
    animationPlaying = false;
  }
}

export { SetFrame, ClonePos, playAnimation, animationPlaying, setAmimationPlaying, getAnimationPlaying };
