import { world, system } from "@minecraft/server";
import { Coroutine, stopBossCoroutines } from "./CoroutineClass";

class BaseBoss {
  constructor(name, entityId, health = 1000, damage = 50) {
    this.entity = world.getEntity(entityId);
    this.name = name;
    this.entityId = entityId;
    this.health = health;
    this.damage = damage;
    this.isActive = false;
    this.isDead = false;
  }

  init() {
    //console.warn(`${this.name} (ID: ${this.entityId}) has entered the battle!`);
    const test = system.runInterval(() => {
      if (!this.entity.isValid()) {
        system.clearRun(test);
      }
      try {
        Coroutine.tickForBoss(this.entityId);
      } catch (error) {
        //console.error("Error in Coroutine.tick:", error);
      }
    });
    this.entity.triggerEvent('lv_mo:reset_ability');
    this.entity.triggerEvent('lv_mo:can_use_ability');
    this.startBehaviorLoop();
  }

  die() {
    if (this.isDead) return;
    stopBossCoroutines(this.entityId)
    this.isDead = true;
    //console.warn(`${this.name} (ID: ${this.entityId}) has been defeated!`);
    this.stopBehaviorLoop();
  }

  async startBehaviorLoop() {
    this.isActive = true;
    //console.log(`${this.name} (ID: ${this.entityId}) has entered the behavior loop.`);
    
    while (this.isActive && !this.isDead) {
      try {
        await this.specialBehavior();
      } catch (error) {
        //console.error(`Error in ${this.name} behavior loop:`, error);
        this.isActive = false;
      }

      if (!this.isDead) {
        await this.wait(60);
      }
    }

    //console.log(`${this.name} (ID: ${this.entityId}) has stopped its behavior loop.`);
  }

  stopBehaviorLoop() {
    this.isActive = false;
  }

  async specialBehavior() {
    // Placeholder for derived classes
  }

  wait(ticks) {
    return new Promise((resolve) => system.runTimeout(() => resolve(), ticks));
  }

  async resetAndReadyAbility() {
    if (!this.entity.isValid()) return;
    this.entity.triggerEvent('lv_mo:reset_ability');
    await this.wait(20);
    if (!this.entity.isValid()) return;
    this.entity.triggerEvent('lv_mo:can_use_ability');
  }

  tipPlayer(radius, text) {
    if (this.isDead || !this.entity.isValid()) return;
    let position = this.entity.location;
    for (let entity of this.getRadiusEntity(position, radius)) {
      //entity.onScreenDisplay.setActionBar(text);
    }

  }

  getRadiusEntity(position, radius, family = ["player"]) {
    if (this.isDead || !this.entity.isValid()) return [];
    return this.entity.dimension.getEntities({
      location: position,
      families: family,
      maxDistance: radius,
    });
  }

  randomAbility(array) {
    let index = Math.floor(Math.random() * array.length);
    return array[index];
  }
}

export default BaseBoss;
