import * as mc from "@minecraft/server";
import { endTest } from "./entities/sculptor";

export function create(entity, location) {
  const timer = entity.dimension.spawnEntity("hf_mzs:timer", location);
  if (timer !== undefined && timer.isValid()) timer.triggerEvent("hf_mzs:start");
  return timer.id;
}

export function pause(id) {
  const timer = mc.world.getEntity(id);
  if (timer !== undefined && timer.isValid()) timer.triggerEvent("hf_mzs:pause");
}

export function remove(id) {
  const timer = mc.world.getEntity(id);
  if (timer !== undefined && timer.isValid()) timer.remove();
}
function over(timer) {
  if (timer !== undefined && timer.isValid()) {
    // mc.world.sendMessage("timer over");
    endTest(mc.world.getEntity(timer.getDynamicProperty("hf_mzs:sculptor")));
  }
}

export function unpause(id) {
  const timer = mc.world.getEntity(id);
  if (timer !== undefined && timer.isValid()) timer.triggerEvent("hf_mzs:start");
}

export function stop(id) {
  const timer = mc.world.getEntity(id);
  if (timer !== undefined && timer.isValid()) timer.remove();
}

export function tick(event) {
  if (event.id === "hf_mzs:timer_tick") {
    const timer = event.sourceEntity;
    if (timer !== undefined && timer.isValid()) {
      const healthComponent = timer.getComponent("minecraft:health");
      if (healthComponent.currentValue > 1) healthComponent.setCurrentValue(healthComponent.currentValue - 1);
      else over(timer);
    }
  }
}
