/* -------------------------------------------- */
import { CrucibleUtility } from "./crucible-utility.js";
import { CrucibleRollDialog } from "./crucible-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 CrucibleActor 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 CrucibleUtility.loadCompendium("fvtt-crucible-rpg.skills");
      data.items = skills.map(i => i.toObject())
    }
    if (data.type == 'npc') {
    }

    return super.create(data, options);
  }

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

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

  /* -------------------------------------------- */
  computeHitPoints() {
    let hp = duplicate(this.data.data.secondary.hp)
    let max = (this.data.data.abilities.str.value + this.data.data.abilities.con.value) * 6
    if (max != hp.max || hp.value > max) {
      hp.max = max
      hp.value = max // Init case
      this.update({ 'data.secondary.hp': hp })
    }
  }
  /* -------------------------------------------- */
  computeEffortPoints() {
    let effort = duplicate(this.data.data.secondary.effort)
    let max = (this.data.data.abilities.con.value + this.data.data.abilities.int.value) * 6
    if (max != effort.max || effort.value > max) {
      effort.max = max
      effort.value = max // Init case
      this.update({ 'data.secondary.effort': effort })
    }
  }

  /* -------------------------------------------- */
  prepareDerivedData() {

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

    super.prepareDerivedData();
  }

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

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

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

  /* -------------------------------------------- */
  getMoneys() {
    let comp = this.data.items.filter(item => item.type == 'money');
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getFeats() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'feat') || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getFeatsWithDie() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'feat' && item.data.data.isfeatdie) || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  getFeatsWithSL() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'feat' && item.data.data.issl) || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getLore() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'spell') || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  getEquippedWeapons() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'weapon' && item.data.data.equipped) || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getArmors() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'armor') || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  getEquippedArmor() {
    let comp = this.data.items.find(item => item.type == 'armor' && item.data.data.equipped)
    if (comp) {
      return duplicate(comp)
    }
    return undefined
  }
  /* -------------------------------------------- */
  getShields() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'shield') || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  getEquippedShield() {
    let comp = this.data.items.find(item => item.type == 'shield' && item.data.data.equipped)
    if (comp) {
      return duplicate(comp)
    }
    return undefined
  }
  /* -------------------------------------------- */
  getRace() {
    let race = this.data.items.filter(item => item.type == 'race')
    return race[0] ?? [];
  }
  /* -------------------------------------------- */
  checkAndPrepareEquipment(item) {
  }

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

  /* -------------------------------------------- */
  getWeapons() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'weapon') || []);
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp;
  }
  /* -------------------------------------------- */
  getItemById(id) {
    let item = this.data.items.find(item => item.id == id);
    if (item) {
      item = duplicate(item)
      if (item.type == 'specialisation') {
        item.data.dice = CrucibleUtility.getDiceFromLevel(item.data.level);
      }
    }
    return item;
  }

  /* -------------------------------------------- */
  getSkills() {
    let comp = duplicate(this.data.items.filter(item => item.type == 'skill') || [])
    for (let skill of comp) {
      CrucibleUtility.updateSkill(skill)
    }
    CrucibleUtility.sortArrayObjectsByName(comp)
    return comp
  }

  /* -------------------------------------------- */
  getRelevantAbility(statKey) {
    let comp = duplicate(this.data.items.filter(item => item.type == 'skill' && item.data.data.ability == ability) || []);
    return comp;
  }


  /* -------------------------------------------- */
  async equipItem(itemId) {
    let item = this.data.items.find(item => item.id == itemId)
    if (item && item.data.data) {
      if (item.type == "armor") {
        let armor = this.data.items.find(item => item.id != itemId && item.type == "armor" && item.data.data.equipped)
        if (armor) {
          ui.notifications.warn("You already have an armor equipped!")
          return
        }
      }
      if (item.type == "shield") {
        let shield = this.data.items.find(item => item.id != itemId && item.type == "shield" && item.data.data.equipped)
        if (shield) {
          ui.notifications.warn("You already have a shield equipped!")
          return
        }
      }
      let update = { _id: item.id, "data.equipped": !item.data.data.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.data.items.filter(item => item.type == 'shield' || item.type == 'armor' || item.type == "weapon" || item.type == "equipment");
  }
  /* ------------------------------------------- */
  getEquipmentsOnly() {
    return duplicate(this.data.items.filter(item => item.type == "equipment") || [])
  }

  /* ------------------------------------------- */
  getSaveRoll() {
    return {
      reflex: {
        "label": "Reflex Save",
        "img": "systems/fvtt-crucible-rpg/images/icons/saves/reflex_save.webp",
        "value": this.data.data.abilities.agi.value + this.data.data.abilities.wit.value
      },
      fortitude: {
        "label": "Fortitude Save",
        "img": "systems/fvtt-crucible-rpg/images/icons/saves/fortitude_save.webp",
        "value": this.data.data.abilities.str.value + this.data.data.abilities.con.value
      },
      willpower: {
        "label": "Willpower Save",
        "img": "systems/fvtt-crucible-rpg/images/icons/saves/will_save.webp",
        "value": this.data.data.abilities.int.value + this.data.data.abilities.cha.value
      }
    }
  }

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

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

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

    // Manages slow effect
    let overCapacity = Math.floor(this.encCurrent / this.getEncumbranceCapacity())
    this.encHindrance = Math.floor(this.encCurrent / this.getEncumbranceCapacity())

    //console.log("Capacity", overCapacity, this.encCurrent / this.getEncumbranceCapacity() )
    let effect = this.data.items.find(item => item.type == "effect" && item.data.data.slow)
    if (overCapacity >= 4) {
      if (!effect) {
        effect = await CrucibleUtility.getEffectFromCompendium("Slowed")
        effect.data.slow = true
        this.createEmbeddedDocuments('Item', [effect])
      }
    } else {
      if (effect) {
        this.deleteEmbeddedDocuments('Item', [effect.id])
      }
    }
  }

  /* -------------------------------------------- */
  getAbility(abilKey) {
    return this.data.data.abilities[abilKey];
  }

  /* -------------------------------------------- */
  async addObjectToContainer(itemId, containerId) {
    let container = this.data.items.find(item => item.id == containerId && item.data.data.iscontainer)
    let object = this.data.items.find(item => item.id == itemId)
    if (container) {
      if (object.data.data.iscontainer) {
        ui.notifications.warn("Only 1 level of container allowed")
        return
      }
      let alreadyInside = this.data.items.filter(item => item.data.data.containerid && item.data.data.containerid == containerId);
      if (alreadyInside.length >= container.data.data.containercapacity) {
        ui.notifications.warn("Container is already full !")
        return
      } else {
        await this.updateEmbeddedDocuments("Item", [{ _id: object.id, 'data.containerid': containerId }])
      }
    } else if (object && object.data.data.containerid) { // remove from container
      console.log("Removeing: ", object)
      await this.updateEmbeddedDocuments("Item", [{ _id: object.id, 'data.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.data.items.find(item => item.id == equipmentId);
    if (item && item.data.data) {
      let update = { _id: item.id, "data.equipped": !item.data.data.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.data.data.subactors) {
      subActors.push(duplicate(game.actors.get(id)))
    }
    return subActors;
  }
  /* -------------------------------------------- */
  async addSubActor(subActorId) {
    let subActors = duplicate(this.data.data.subactors);
    subActors.push(subActorId);
    await this.update({ 'data.subactors': subActors });
  }
  /* -------------------------------------------- */
  async delSubActor(subActorId) {
    let newArray = [];
    for (let id of this.data.data.subactors) {
      if (id != subActorId) {
        newArray.push(id);
      }
    }
    await this.update({ 'data.subactors': newArray });
  }

  /* -------------------------------------------- */
  syncRoll(rollData) {
    this.lastRollId = rollData.rollId;
    CrucibleUtility.saveRollData(rollData);
  }

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

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

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

  /* -------------------------------------------- */
  async incrementSkillExp(skillId, inc) {
    let skill = this.data.items.get(skillId)
    if (skill) {
      await this.updateEmbeddedDocuments('Item', [{ _id: skill.id, 'data.exp': skill.data.data.exp + inc }])
      let chatData = {
        user: game.user.id,
        rollMode: game.settings.get("core", "rollMode"),
        whisper: [game.user.id].concat(ChatMessage.getWhisperRecipients('GM')),
        content: `<div>${this.name} has gained 1 exp in the skill ${skill.name} (exp = ${skill.data.data.exp})</div`
      }
      ChatMessage.create(chatData)
      if (skill.data.data.exp >= 25) {
        await this.updateEmbeddedDocuments('Item', [{ _id: skill.id, 'data.exp': 0, 'data.explevel': skill.data.data.explevel + 1 }])
        let chatData = {
          user: game.user.id,
          rollMode: game.settings.get("core", "rollMode"),
          whisper: [game.user.id].concat(ChatMessage.getWhisperRecipients('GM')),
          content: `<div>${this.name} has gained 1 exp SL in the skill ${skill.name} (new exp SL :  ${skill.data.data.explevel}) !</div`
        }
        ChatMessage.create(chatData)
      }
    }
  }

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

  /* -------------------------------------------- */
  getCommonRollData(abilityKey = undefined) {
    let rollData = CrucibleUtility.getBasicRollData()
    rollData.alias = this.name
    rollData.actorImg = this.img
    rollData.actorId = this.id
    rollData.img = this.img
    rollData.featsDie = this.getFeatsWithDie()
    rollData.featsSL = this.getFeatsWithSL()
    rollData.armors = this.getArmors()
    rollData.featDieName = "none"
    rollData.featSLName = "none"
    rollData.rollAdvantage = "none"
    rollData.advantage = "none"
    rollData.disadvantage = "none"

    if (abilityKey) {
      rollData.ability = this.getAbility(abilityKey)
      //rollData.skillList = this.getRelevantSkill(abilityKey)
      rollData.selectedKill = undefined
    }

    console.log("ROLLDATA", rollData)

    return rollData
  }

  /* -------------------------------------------- */
  rollAbility(abilityKey) {
    let rollData = this.getCommonRollData(abilityKey)
    rollData.mode = "ability"
    CrucibleUtility.rollCrucible(rollData)
  }

  /* -------------------------------------------- */
  rollSkill(skillId) {
    let skill = this.data.items.get(skillId)
    if (skill) {
      if (skill.data.islore && skill.data.level == 0) {
        ui.notifications.warn("You can't use Lore Skills with a SL of 0.")
        return
      }
      skill = duplicate(skill)
      CrucibleUtility.updateSkill(skill)
      let abilityKey = skill.data.ability
      let rollData = this.getCommonRollData(abilityKey)
      rollData.mode = "skill"
      rollData.skill = skill
      rollData.img = skill.img

      this.startRoll(rollData)
    }
  }

  /* -------------------------------------------- */
  rollWeapon(weaponId) {
    let weapon = this.data.items.get(weaponId)
    if (weapon) {
      weapon = duplicate(weapon)
      let skill = this.data.items.find(item => item.name.toLowerCase() == weapon.data.skill.toLowerCase())
      if (skill) {
        skill = duplicate(skill)
        CrucibleUtility.updateSkill(skill)
        let abilityKey = skill.data.ability
        let rollData = this.getCommonRollData(abilityKey)
        rollData.mode = "weapon"
        rollData.skill = skill
        rollData.weapon = weapon
        rollData.img = weapon.img

        this.startRoll(rollData)
      } else {
        ui.notifications.warn("Unable to find the relevant skill for weapon " + weapon.name)
      }
    }
  }

  /* -------------------------------------------- */
  rollShieldDie() {
    let shield = this.getEquippedShield()
    if (shield) {
      shield = duplicate(shield)
      let rollData = this.getCommonRollData()
      rollData.mode = "shield"
      rollData.shield = shield
      rollData.img = shield.img
      this.startRoll(rollData)
    }
  }

  /* -------------------------------------------- */
  rollArmorDie() {
    let armor = this.getEquippedArmor()
    if (armor) {
      armor = duplicate(armor)
      let diceValue = armor.data.absorprionroll
      
    }
  }

  /* -------------------------------------------- */
  rollSave(saveKey) {
    let saves = this.getSaveRoll()
    let save = saves[saveKey]
    if (save) {
      save = duplicate(save)
      let rollData = this.getCommonRollData()
      rollData.mode = "save"
      rollData.save = save
      //rollData.img = skill.img

      this.startRoll(rollData)
    }

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

}
