/* -------------------------------------------- */
import { Hero6Utility } from "./hero6-utility.js";
import { Hero6RollDialog } from "./hero6-roll-dialog.js";

/* -------------------------------------------- */
const coverBonusTable = { "nocover": 0, "lightcover": 2, "heavycover": 4, "entrenchedcover": 6 };
const statThreatLevel = ["agi", "str", "phy", "com", "def", "per"]
const __subkey2title = {
  "melee-dmg": "Melee Damage", "melee-atk": "Melee Attack", "ranged-atk": "Ranged Attack",
  "ranged-dmg": "Ranged Damage", "dmg-res": "Damare Resistance"
}

/* -------------------------------------------- */
/* -------------------------------------------- */
/**
 * Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
 * @extends {Actor}
 */
export class Hero6Actor extends Actor {

  /* -------------------------------------------- */
  /**
   * Override the create() function to provide additional SoS functionality.
   *
   * This overrided create() function adds initial items 
   * Namely: Basic skills, money, 
   *
   * @param {Object} data        Barebones actor data which this function adds onto.
   * @param {Object} options     (Unused) Additional options which customize the creation workflow.
   *
   */

  static async create(data, options) {

    // Case of compendium global import
    if (data instanceof Array) {
      return super.create(data, options);
    }
    // If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
    if (data.items) {
      let actor = super.create(data, options);
      return actor;
    }

    if (data.type == 'character') {
      //const skills = await Hero6Utility.loadCompendium("fvtt-hero-system-6.skills");
      //data.items = skills.map(i => i.toObject())
    }
    if (data.type == 'npc') {
    }

    return super.create(data, options);
  }

  /* -------------------------------------------- */
  prepareBaseData() {
  }

  /* -------------------------------------------- */
  async prepareData() {
    super.prepareData();
  }

  /* -------------------------------------------- */
  computeHitPoints() {
    if (this.type == "character") {
    }
  }
  /* -------------------------------------------- */
  prepareDerivedData() {

    if (this.type == 'character' || game.user.isGM) {
      this.system.encCapacity = this.getEncumbranceCapacity()
      this.buildContainerTree()
      this.computeHitPoints()
    }

    super.prepareDerivedData();
  }

  /* -------------------------------------------- */
  _preUpdate(changed, options, user) {

    super._preUpdate(changed, options, user);
  }

  /* -------------------------------------------- */
  getEncumbranceCapacity() {
    return 1;
  }

  /* -------------------------------------------- */
  getMoneys() {
    let comp = this.items.filter(item => item.type == 'currency');
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp;
  }
  getEquippedWeapons() {
    let comp = duplicate(this.items.filter(item => item.type == 'weapon' && item.system.equipped) || []);
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getArmors() {
    let comp = duplicate(this.items.filter(item => item.type == 'armor') || []);
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp;
  }
  getEquippedArmor() {
    let comp = this.items.find(item => item.type == 'armor' && item.system.equipped)
    if (comp) {
      return duplicate(comp)
    }
    return undefined
  }
  /* -------------------------------------------- */
  getShields() {
    let comp = duplicate(this.items.filter(item => item.type == 'shield') || []);
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp;
  }
  getEquippedShield() {
    let comp = this.items.find(item => item.type == 'shield' && item.system.equipped)
    if (comp) {
      return duplicate(comp)
    }
    return undefined
  }
  /* -------------------------------------------- */
  getRace() {
    let race = this.items.filter(item => item.type == 'race')
    return race[0] ?? [];
  }
  /* -------------------------------------------- */
  checkAndPrepareEquipment(item) {
  }

  /* -------------------------------------------- */
  checkAndPrepareEquipments(listItem) {
    for (let item of listItem) {
      this.checkAndPrepareEquipment(item)
    }
    return listItem
  }

  /* -------------------------------------------- */
  getConditions() {
    let comp = duplicate(this.items.filter(item => item.type == 'condition') || []);
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getWeapons() {
    let comp = duplicate(this.items.filter(item => item.type == 'weapon') || []);
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getItemById(id) {
    let item = this.items.find(item => item.id == id);
    if (item) {
      item = duplicate(item)
    }
    return item;
  }
  /* -------------------------------------------- */
  prepareSkill(skill) {
    skill.roll = 0
    skill.charac = "N/A"
    if (skill.system.skillfamiliarity) {
      skill.roll = 8;
    } else if (skill.system.skillprofiency) {
      skill.roll = 10;
    } else if (skill.system.skilltype == "agility") {
      skill.charac = "DEX"
      let charac = duplicate(this.system.characteristics.dex)
      this.prepareCharacValues(charac)
      skill.roll = charac.roll
    } else if (skill.system.skilltype == "interaction") {
      skill.charac = "PRE"
      let charac = duplicate(this.system.characteristics.pre)
      this.prepareCharacValues(charac)
      skill.roll = charac.roll
    } else if (skill.system.skilltype == "intellect") {
      skill.charac = "INT"
      let charac = duplicate(this.system.characteristics.int)
      this.prepareCharacValues(charac)
      skill.roll = charac.roll
    } else if (skill.system.skilltype == "background") {
      skill.roll = 11
    } else if (skill.system.skilltype == "custom") {
      if (skill.system.characteristic == "manual") {
        skill.roll = skill.system.base
      } else {
        skill.charac = skill.system.characteristic
        let charac = duplicate(this.system.characteristics[skill.system.characteristic])
        this.prepareCharacValues(charac)
        skill.roll = charac.roll
      }
    }
    if (skill.system.levels > 0) {
      skill.roll += skill.system.levels
    }
  }

  /* -------------------------------------------- */
  getSkills() {
    let comp = duplicate(this.items.filter(item => item.type == 'skill') || [])
    for (let skill of comp) {
      this.prepareSkill(skill)
    }
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp
  }
  getPerks() {
    let comp = duplicate(this.items.filter(item => item.type == 'perk') || [])
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp
  }
  async getPowers() {
    let comp = duplicate(this.items.filter(item => item.type == 'power') || [])
    for (let c of comp) {
      c.enrichDescription = c.name + "<br>" + await TextEditor.enrichHTML(c.system.description, { async: true })
    }
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp
  }
  getTalents() {
    let comp = duplicate(this.items.filter(item => item.type == 'talent') || [])
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp
  }
  getMartialArts() {
    let comp = duplicate(this.items.filter(item => item.type == 'martialart') || [])
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp
  }
  getComplications() {
    let comp = duplicate(this.items.filter(item => item.type == 'complication') || [])
    Hero6Utility.sortArrayObjectsByName(comp)
    return comp
  }

  /* -------------------------------------------- */
  async equipItem(itemId) {
    let item = this.items.find(item => item.id == itemId)
    if (item && item.system) {
      if (item.type == "armor") {
        let armor = this.items.find(item => item.id != itemId && item.type == "armor" && item.system.equipped)
        if (armor) {
          ui.notifications.warn("You already have an armor equipped!")
          return
        }
      }
      if (item.type == "shield") {
        let shield = this.items.find(item => item.id != itemId && item.type == "shield" && item.system.equipped)
        if (shield) {
          ui.notifications.warn("You already have a shield equipped!")
          return
        }
      }
      let update = { _id: item.id, "system.equipped": !item.system.equipped };
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }

  /* -------------------------------------------- */
  compareName(a, b) {
    if (a.name < b.name) {
      return -1;
    }
    if (a.name > b.name) {
      return 1;
    }
    return 0;
  }

  /* ------------------------------------------- */
  getEquipments() {
    return this.items.filter(item => item.type == "equipment" && item.system.subtype == "equipment");
  }
  getWeapons() {
    return this.items.filter(item => item.type == "equipment" && item.system.subtype == "weapon");
  }
  getArmors() {
    return this.items.filter(item => item.type == "equipment" && item.system.subtype == "armor");
  }
  getShields() {
    return this.items.filter(item => item.type == "equipment" && item.system.subtype == "shield");
  }
  /* ------------------------------------------- */
  getEquipmentsOnly() {
    return duplicate(this.items.filter(item => item.type == "equipment" && item.system.subtype == "equipment") || [])
  }

  /* ------------------------------------------- */
  async buildContainerTree() {
    let equipments = duplicate(this.items.filter(item => item.type == "equipment") || [])
    for (let equip1 of equipments) {
      if (equip1.system.iscontainer) {
        equip1.system.contents = []
        equip1.system.contentsEnc = 0
        for (let equip2 of equipments) {
          if (equip1._id != equip2.id && equip2.system.containerid == equip1.id) {
            equip1.system.contents.push(equip2)
            let q = equip2.system.quantity ?? 1
            equip1.system.contentsEnc += q * equip2.system.weight
          }
        }
      }
    }

    // Compute whole enc
    let enc = 0
    for (let item of equipments) {
      //item.data.idrDice = Hero6Utility.getDiceFromLevel(Number(item.data.idr))
      if (item.system.equipped) {
        if (item.system.iscontainer) {
          enc += item.system.contentsEnc
        } else if (item.system.containerid == "") {
          let q = item.system.quantity ?? 1
          enc += q * item.system.weight
        }
      }
    }
    for (let item of this.items) { // Process items/shields/armors
      if ((item.type == "weapon" || item.type == "shield" || item.type == "armor") && item.system.equipped) {
        let q = item.system.quantity ?? 1
        enc += q * item.system.weight
      }
    }

    // Store local values
    this.encCurrent = enc
    this.containersTree = equipments.filter(item => item.system.containerid == "") // Returns the root of equipements without container

  }

  /* -------------------------------------------- */
  async incDecHP(formula) {
    let dmgRoll = new Roll(formula + "[dark-starsorange]").roll({ async: false })
    await Hero6Utility.showDiceSoNice(dmgRoll, game.settings.get("core", "rollMode"))
    let hp = duplicate(this.system.secondary.hp)
    hp.value = Number(hp.value) + Number(dmgRoll.total)
    this.update({ 'system.secondary.hp': hp })
    return Number(dmgRoll.total)
  }

  /* -------------------------------------------- */
  async addObjectToContainer(itemId, containerId) {
    let container = this.items.find(item => item.id == containerId && item.system.iscontainer)
    let object = this.items.find(item => item.id == itemId)
    if (container) {
      if (object.system.iscontainer) {
        ui.notifications.warn("Only 1 level of container allowed")
        return
      }
      let alreadyInside = this.items.filter(item => item.system.containerid && item.system.containerid == containerId);
      if (alreadyInside.length >= container.system.containercapacity) {
        ui.notifications.warn("Container is already full !")
        return
      } else {
        await this.updateEmbeddedDocuments("Item", [{ _id: object.id, 'system.containerid': containerId }])
      }
    } else if (object && object.system.containerid) { // remove from container
      console.log("Removeing: ", object)
      await this.updateEmbeddedDocuments("Item", [{ _id: object.id, 'system.containerid': "" }]);
    }
  }

  /* -------------------------------------------- */
  async preprocessItem(event, item, onDrop = false) {
    let dropID = $(event.target).parents(".item").attr("data-item-id") // Only relevant if container drop
    let objectID = item.id || item._id
    this.addObjectToContainer(objectID, dropID)
    return true
  }

  /* -------------------------------------------- */
  async equipGear(equipmentId) {
    let item = this.items.find(item => item.id == equipmentId);
    if (item && item.system) {
      let update = { _id: item.id, "system.equipped": !item.system.equipped };
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }
  /* -------------------------------------------- */
  getInitiativeScore(combatId, combatantId) {
    if (this.type == 'character') {
      this.rollMR(true, combatId, combatantId)
    }
    console.log("Init required !!!!")
    return -1;
  }

  /* -------------------------------------------- */
  getSubActors() {
    let subActors = [];
    for (let id of this.system.subactors) {
      subActors.push(duplicate(game.actors.get(id)))
    }
    return subActors;
  }
  /* -------------------------------------------- */
  async addSubActor(subActorId) {
    let subActors = duplicate(this.system.subactors);
    subActors.push(subActorId);
    await this.update({ 'system.subactors': subActors });
  }
  /* -------------------------------------------- */
  async delSubActor(subActorId) {
    let newArray = [];
    for (let id of this.system.subactors) {
      if (id != subActorId) {
        newArray.push(id);
      }
    }
    await this.update({ 'system.subactors': newArray });
  }

  /* -------------------------------------------- */
  prepareCharacValues(charac) {
    charac.total = charac.value
    charac.roll = 9 + Math.floor((charac.value) / 5)
  }
  prepareCharac() {
    let characs = duplicate(this.system.characteristics)
    for (let key in characs) {
      this.prepareCharacValues(characs[key])
    }
    return characs
  }

  /* -------------------------------------------- */
  getOneSkill(skillId) {
    let skill = this.items.find(item => item.type == 'skill' && item.id == skillId)
    if (skill) {
      skill = duplicate(skill);
    }
    return skill;
  }

  /* -------------------------------------------- */
  async deleteAllItemsByType(itemType) {
    let items = this.items.filter(item => item.type == itemType);
    await this.deleteEmbeddedDocuments('Item', items);
  }

  /* -------------------------------------------- */
  async addItemWithoutDuplicate(newItem) {
    let item = this.items.find(item => item.type == newItem.type && item.name.toLowerCase() == newItem.name.toLowerCase())
    if (!item) {
      await this.createEmbeddedDocuments('Item', [newItem]);
    }
  }

  /* -------------------------------------------- */
  async incDecQuantity(objetId, incDec = 0) {
    let objetQ = this.items.get(objetId)
    if (objetQ) {
      let newQ = objetQ.system.quantity + incDec
      if (newQ >= 0) {
        const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'system.quantity': newQ }]) // pdates one EmbeddedEntity
      }
    }
  }
  /* -------------------------------------------- */
  async incDecAmmo(objetId, incDec = 0) {
    let objetQ = this.items.get(objetId)
    if (objetQ) {
      let newQ = objetQ.system.ammocurrent + incDec;
      if (newQ >= 0 && newQ <= objetQ.system.ammomax) {
        const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'system.ammocurrent': newQ }]); // pdates one EmbeddedEntity
      }
    }
  }

  /* -------------------------------------------- */
  getCommonRollData(chKey = undefined) {
    let rollData = Hero6Utility.getBasicRollData()
    rollData.alias = this.name
    rollData.actorImg = this.img
    rollData.actorId = this.id
    rollData.img = this.img
    if (chKey) {
      rollData.charac = duplicate(this.system.characteristics[chKey])
      this.prepareCharacValues(rollData.charac)
    }
    if (rollData.defenderTokenId) {
      let defenderToken = game.canvas.tokens.get(rollData.defenderTokenId)
      let defender = defenderToken.actor

      // Distance management
      let token = this.token
      if (!token) {
        let tokens = this.getActiveTokens()
        token = tokens[0]
      }
      if (token) {
        const ray = new Ray(token.object?.center || token.center, defenderToken.center)
        rollData.tokensDistance = canvas.grid.measureDistances([{ ray }], { gridSpaces: false })[0] / canvas.grid.grid.options.dimensions.distance
      } else {
        ui.notifications.info("No token connected to this actor, unable to compute distance.")
        return
      }
      if (defender) {
        rollData.forceAdvantage = defender.isAttackerAdvantage()
        rollData.advantageFromTarget = true
      }
    }
    console.log("ROLLDATA", rollData)

    return rollData
  }

  /* -------------------------------------------- */
  rollCharac(chKey) {
    let rollData = this.getCommonRollData(chKey)
    rollData.mode = "charac"
    if (rollData.target) {
      ui.notifications.warn("You are targetting a token with a skill : please use a Weapon instead.")
      return
    }
    this.startRoll(rollData)
  }
  /* -------------------------------------------- */
  rollItem(itemId) {
    let item = this.items.get(itemId)
    let rollData = this.getCommonRollData()
    rollData.mode = "item"
    rollData.item = duplicate(item)
    if ( item.type == "skill") {
      this.prepareSkill(rollData.item)
    }
    this.startRoll(rollData)
  }

  /* -------------------------------------------- */
  rollSkill(skillId) {
    let skill = this.items.get(skillId)
    if (skill) {
      if (skill.system.islore && skill.system.level == 0) {
        ui.notifications.warn("You can't use Lore Skills with a SL of 0.")
        return
      }
      skill = duplicate(skill)
      Hero6Utility.updateSkill(skill)
      let abilityKey = skill.system.ability
      let rollData = this.getCommonRollData(abilityKey)
      rollData.mode = "skill"
      rollData.skill = skill
      rollData.img = skill.img
      if (rollData.target) {
        ui.notifications.warn("You are targetting a token with a skill : please use a Weapon instead.")
        return
      }
      this.startRoll(rollData)
    }
  }

  /* -------------------------------------------- */
  rollWeapon(weaponId) {
    let weapon = this.items.get(weaponId)
    if (weapon) {
      weapon = duplicate(weapon)
      let skill = this.items.find(item => item.name.toLowerCase() == weapon.system.skill.toLowerCase())
      if (skill) {
        skill = duplicate(skill)
        Hero6Utility.updateSkill(skill)
        let abilityKey = skill.system.ability
        let rollData = this.getCommonRollData(abilityKey)
        rollData.mode = "weapon"
        rollData.skill = skill
        rollData.weapon = weapon
        rollData.img = weapon.img
        if (!rollData.forceDisadvantage) { // This is an attack, check if disadvantaged
          rollData.forceDisadvantage = this.isAttackDisadvantage()
        }
        /*if (rollData.weapon.system.isranged && rollData.tokensDistance > Hero6Utility.getWeaponMaxRange(rollData.weapon) ) {
          ui.notifications.warn(`Your target is out of range of your weapon (max: ${Hero6Utility.getWeaponMaxRange(rollData.weapon)}  - current : ${rollData.tokensDistance})` )
          return
        }*/
        this.startRoll(rollData)
      } else {
        ui.notifications.warn("Unable to find the relevant skill for weapon " + weapon.name)
      }
    }
  }

  /* -------------------------------------------- */
  async startRoll(rollData) {
    let rollDialog = await Hero6RollDialog.create(this, rollData)
    rollDialog.render(true)
  }

}
