import { Vector3, world } from "@minecraft/server";
import Level from "./level";
import pupeteer from "../pupeteer";
import { teleportAgent, isAgentAt, getAgentLocation, getAgent } from "../utils/agentUtils";
import { startLevel } from "../utils/levelUtils";
import { vector3, Vector3Add, Vector3ToCommandString } from "../utils/vectorUtils";
import { mindKeeper, CURRENT_LEVEL } from "../../main";
import { MinecraftBlockTypes } from "../../vanilla-data/mojang-block";

class AbstractAgentTrackMission extends Level {
  levelid: string;
  constructor(
    levelid: string,
    agentStartPositon: Vector3,
    agentEndPosition: Vector3,
    startLevelCommandBlockPos: Vector3
  ) {
    super(
      () => {
        pupeteer.sendWorldMessage(`%message.${levelid}.started`);
        pupeteer.setTitleTimed(`%message.${levelid}.name`, 2.5);
        startLevel(startLevelCommandBlockPos);
        teleportAgent(agentStartPositon);
      },
      () => {
        pupeteer.setActionBar(`%message.${levelid}.make`);
      },
      () => {
        pupeteer.clearActionBar();
        pupeteer.sendWorldMessage(`%message.${levelid}.complete`);
        pupeteer.setTitleTimed(`%message.${levelid}.complete`, 2.5);

        mindKeeper.increment(CURRENT_LEVEL);
      },
      () => {
        let isComplete = false;
        let isOutOfBounds = false;

        let agentPos = getAgentLocation();
        let blockLava = world.getDimension("overworld").getBlock(Vector3Add(agentPos, vector3(0, -7, 0)));
        let blockAir = world.getDimension("overworld").getBlock(Vector3Add(agentPos, vector3(0, -1, 0)));

        if (
          blockLava &&
          blockLava.type.id === MinecraftBlockTypes.Lava &&
          blockAir &&
          blockAir.type.id === MinecraftBlockTypes.Air
        ) {
          isOutOfBounds = true;
        }

        if (isAgentAt(agentEndPosition)) {
          isComplete = true;
        }

        if (isOutOfBounds) {
          pupeteer.sendWorldMessage(`%message.outofbounds`);
          pupeteer.setTitleTimed(`%message.outofbounds`, 2.5);
          // world.getDimension("overworld").runCommand("/kill @e[type=agent]");
          world.getDimension("overworld").runCommand("execute as @p run codebuilder runtime stop @s");

          teleportAgent(agentStartPositon);
          return false;
        } else if (isComplete) {
          return true;
        }
        return false;
      }
    );
    this.levelid = levelid;
  }
}

export default AbstractAgentTrackMission;
