/* -------------------------------------------- */
import { WastelandUtility } from "./wasteland-utility.js";
import { WastelandRollDialog } from "./applications/wasteland-roll-dialog.mjs";

/* -------------------------------------------- */
const __degatsBonus = [-2, -2, -1, -1, 0, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 8, 8, 9, 9, 10, 10]
const __vitesseBonus = [-2, -2, -1, -1, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8]

/* -------------------------------------------- */
/**
 * Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
 * @extends {Actor}
 */
export class WastelandActor 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;
    }

    const skills = await WastelandUtility.loadCompendium("fvtt-wasteland.skills")
    if (data.type == 'personnage') {
      data.items = skills.map(i => i.toObject())
    }
    if (data.type == 'creature') {
      data.items = skills.filter(i=>i.name.toLowerCase().includes("mêlée")).map(i => i.toObject())
    }

    return super.create(data, options);
  }

  /* -------------------------------------------- */
  prepareArme(arme) {
    arme = foundry.utils.duplicate(arme)
    let combat = this.getCombatValues()
    if (arme.system.typearme == "contact" || arme.system.typearme == "contactjet") {
      arme.system.isMelee = true
      arme.system.competence = foundry.utils.duplicate(this.items.find(item => item.type == "competence" && item.name.toLowerCase() == "mêlée"))
      arme.system.attrKey = "pui"
      arme.system.totalDegats = arme.system.degats + "+" + combat.bonusDegatsTotal
      arme.system.totalOffensif = this.system.attributs.pui.value + arme.system.competence.system.niveau + arme.system.bonusmaniementoff
      if (arme.system.isdefense) {
        arme.system.totalDefensif = combat.defenseTotal + arme.system.competence.system.niveau + arme.system.bonusmaniementdef
      }
    }
    if (arme.system.typearme == "jet" || arme.system.typearme == "tir") {
      arme.system.isDistance = true
      arme.system.competence = foundry.utils.duplicate(this.items.find(item => item.type == "competence" && item.name.toLowerCase() == "armes à distance"))
      arme.system.attrKey = "adr"
      arme.system.totalOffensif = this.system.attributs.adr.value + arme.system.competence.system.niveau + arme.system.bonusmaniementoff
      arme.system.totalDegats = arme.system.degats
      if (arme.system.isdefense) {
        arme.system.totalDefensif = combat.defenseTotal + arme.system.competence.system.niveau + arme.system.bonusmaniementdef
      }
    }
    return arme
  }
  /* -------------------------------------------- */
  prepareBouclier(bouclier) {
    bouclier = foundry.utils.duplicate(bouclier)
    let combat = this.getCombatValues()
    bouclier.system.competence = foundry.utils.duplicate(this.items.find(item => item.type == "competence" && item.name.toLowerCase() == "mêlée"))
    bouclier.system.attrKey = "pui"
    bouclier.system.totalDegats = bouclier.system.degats + "+" + combat.bonusDegatsTotal
    bouclier.system.totalOffensif = this.system.attributs.pui.value + bouclier.system.competence.system.niveau
    bouclier.system.isdefense = true
    bouclier.system.bonusmaniementoff = 0
    bouclier.system.totalDefensif = combat.defenseTotal + bouclier.system.competence.system.niveau + bouclier.system.bonusdefense
    return bouclier
  }

  /* -------------------------------------------- */
  getWeapons() {
    let armes = []
    for (let arme of this.items) {
      if (arme.type == "arme") {
        armes.push(this.prepareArme(arme))
      }
      if (arme.type == "bouclier") {
        armes.push(this.prepareBouclier(arme))
      }
    }
    WastelandUtility.sortArrayObjectsByName(armes)
    return armes
  }

  /* -------------------------------------------- */
  getItemSorted( types) {
    let items = this.items.filter(item => types.includes(item.type )) || []
    WastelandUtility.sortArrayObjectsByName(items)
    return items
  }
  getCharmes() {
    let items = this.items.filter(item => item.type=="charme" && item.system?.charmetype == "charme") || []
    WastelandUtility.sortArrayObjectsByName(items)
    return items
  }
  getTours() {
    let items = this.items.filter(item => item.type=="charme" && item.system?.charmetype == "tour") || []
    WastelandUtility.sortArrayObjectsByName(items)
    return items
  }
  getArtifex() {
    return this.getItemSorted(["artifex"])
  }
  getCapacites() {
    return this.getItemSorted(["capacite"])
  }
  getPouvoirs() {
    return this.getItemSorted(["pouvoir"])
  }
  getDons() {
    return this.getItemSorted(["don"])
  }
  getHubris() {
    return this.getItemSorted(["hubris"])
  }
  getEquipments() {
    return this.getItemSorted(["equipement"])
  }
  getMonnaies() {
    return this.getItemSorted(["monnaie"])
  }
  getMutations() {
    return this.getItemSorted(["mutation"])
  }
  getArmors() {
    return this.getItemSorted(["protection"])
  }
  getPeuple() {
    return this.items.find(item => item.type == "peuple")
  }
  getOrigine() {
    return this.items.find(item => item.type == "origine")
  }
  getMetier() {
    return this.items.find(item => item.type == "metier")
  }
  getHeritage() {
    return this.items.find(item => item.type == "heritage")
  }
  /* -------------------------------------------- */
  getSkills() {
    let comp = []
    for (let item of this.items) {
      item = foundry.utils.duplicate(item)
      if (item.type == "competence") {
        item.system.attribut1total = item.system.niveau + (this.system.attributs[item.system.attribut1]?.value || 0)
        item.system.attribut2total = item.system.niveau + (this.system.attributs[item.system.attribut2]?.value || 0)
        item.system.attribut3total = item.system.niveau + (this.system.attributs[item.system.attribut3]?.value || 0)
        if (item.system.niveau == 0) {
          item.system.attribut1total -= 3
          item.system.attribut2total -= 3
          item.system.attribut3total -= 3
        }
        item.system.attribut1label = this.system.attributs[item.system.attribut1]?.label || ""
        item.system.attribut2label = this.system.attributs[item.system.attribut2]?.label || ""
        item.system.attribut3label = this.system.attributs[item.system.attribut3]?.label || ""
        comp.push(item)
      }
    }
    WastelandUtility.sortArrayObjectsByName(comp)
    return comp
  }

  /* -------------------------------------------- */
  getDefenseBase() {
    return this.system.attributs.tre.value + 5
  }

  /* -------------------------------------------- */
  getVitesseBase() {
    return 5 + __vitesseBonus[this.system.attributs.adr.value]
  }

  /* -------------------------------------------- */
  getCombatValues() {
    let combat = {
      initBase: this.system.attributs.adr.value,
      initTotal: this.system.attributs.adr.value + this.system.combat.initbonus,
      bonusDegats: this.getBonusDegats(),
      bonusDegatsTotal: this.getBonusDegats() + this.system.combat.bonusdegats,
      vitesseBase: this.getVitesseBase(),
      vitesseTotal: this.getVitesseBase() + this.system.combat.vitessebonus,
      defenseBase: this.getDefenseBase(),
      defenseTotal: this.getDefenseBase() + this.system.combat.defensebonus
    }
    return combat
  }

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

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

    if (this.type == 'personnage') {
      this.system.sante.base = this.system.sante.bonus + (this.system.attributs.pui.value + this.system.attributs.tre.value) * 2 + 5
      this.system.psyche.fullmax = ((this.system.attributs.cla.value + this.system.attributs.tre.value) * 2) + 5
    }

    super.prepareDerivedData()
  }

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

    super._preUpdate(changed, options, user);
  }
  /* -------------------------------------------- */
  incDecSante(value) {
    let sante = foundry.utils.duplicate(this.system.sante)
    sante.letaux += value
    this.update({ 'system.sante': sante })
  }
  /* -------------------------------------------- */
  getItemById(id) {
    let item = this.items.find(item => item.id == id);
    if (item) {
      item = foundry.utils.duplicate(item)
    }
    return item;
  }

  /* -------------------------------------------- */
  async equipItem(itemId) {
    let item = this.items.find(item => item.id == itemId)
    if (item?.system) {
      let update = { _id: item.id, "system.equipped": !item.system.equipped }
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }

  /* -------------------------------------------- */
  editItemField(itemId, itemType, itemField, dataType, value) {
    let item = this.items.find(item => item.id == itemId)
    if (item) {
      console.log("Item ", item, itemField, dataType, value)
      if (dataType.toLowerCase() == "number") {
        value = Number(value)
      } else {
        value = String(value)
      }
      let update = { _id: item.id, [`system.${itemField}`]: value };
      this.updateEmbeddedDocuments("Item", [update])
    }
  }

  /* -------------------------------------------- */
  getBonneAventure() {
    return this.system.bonneaventure.actuelle
  }

  /* -------------------------------------------- */
  changeBonneAventure(value) {
    let newBA = this.system.bonneaventure.actuelle
    newBA += value
    this.update({ 'system.bonneaventure.actuelle': newBA })
  }

  /* -------------------------------------------- */
  getEclat() {
    return this.system.eclat.value
  }

  /* -------------------------------------------- */
  changeEclat(value) {
    let newE = this.system.eclat.value
    newE += value
    // Empêcher que l'éclat devienne négatif
    if (newE < 0) {
      newE = 0
    }
    this.update({ 'system.eclat.value': newE })
  }

  /* -------------------------------------------- */
  subPointsPsyche(value) {
    let psyche = foundry.utils.duplicate(this.system.psyche)
    psyche.currentmax -= value
    this.update( {'system.psyche': psyche})
  }

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

  /* -------------------------------------------- */
  getAttribute(attrKey) {
    return this.system.attributes[attrKey]
  }

  /* -------------------------------------------- */
  getBonusDegats() {
    return __degatsBonus[this.system.attributs.pui.value]
  }

  /* -------------------------------------------- */
  async equipGear(equipmentId) {
    let item = this.items.find(item => item.id == equipmentId);
    if (item?.system) {
      let update = { _id: item.id, "system.equipped": !item.system.equipped };
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }

  /* -------------------------------------------- */
  getSubActors() {
    let subActors = [];
    for (let id of this.system.subactors) {
      subActors.push(foundry.utils.duplicate(game.actors.get(id)));
    }
    return subActors;
  }
  /* -------------------------------------------- */
  async addSubActor(subActorId) {
    let subActors = foundry.utils.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 });
  }

  /* -------------------------------------------- */
  async incDecQuantity(objetId, incDec = 0) {
    let objetQ = this.items.get(objetId)
    if (objetQ) {
      let newQ = objetQ.system.quantite + incDec;
      await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'system.quantite': newQ }]); // pdates one EmbeddedEntity
    }
  }
  /* -------------------------------------------- */
  getCompetence(compId) {
    return this.items.get(compId)
  }

  /* -------------------------------------------- */
  async setPredilectionUsed(compId, predIdx) {
    let comp = this.items.get(compId)
    let pred = foundry.utils.duplicate(comp.system.predilections)
    pred[predIdx].used = true
    await this.updateEmbeddedDocuments('Item', [{ _id: compId, 'system.predilections': pred }])
  }

  /* -------------------------------------------- */
  async resetAllPredilections() {
    let updates = []
    for (let item of this.items) {
      if (item.type === "competence" && item.system.predilections && item.system.predilections.length > 0) {
        let pred = foundry.utils.duplicate(item.system.predilections)
        let hasUsed = false
        for (let p of pred) {
          if (p.used) {
            p.used = false
            hasUsed = true
          }
        }
        if (hasUsed) {
          updates.push({ _id: item.id, 'system.predilections': pred })
        }
      }
    }
    if (updates.length > 0) {
      await this.updateEmbeddedDocuments('Item', updates)
      ui.notifications.info(`${updates.length} prédilection(s) réinitialisée(s) pour ${this.name}`)
    } else {
      ui.notifications.info(`Aucune prédilection à réinitialiser pour ${this.name}`)
    }
  }

  /* -------------------------------------------- */
  getInitiativeScore( ) {
    return Number(this.system.attributs.adr.value) + Number(this.system.combat.initbonus)
  }
  /* -------------------------------------------- */
  getBestDefenseValue() {
    let defenseList = this.items.filter(item => (item.type =="arme" || item.type == "bouclier") && item.system.equipped)
    let maxDef = 0
    let bestArme
    for(let arme of defenseList) {
      if (arme.type == "arme" && arme.system.isdefense) {
        arme = this.prepareArme(arme)
      }
      if (arme.type == "bouclier" ) {
        arme = this.prepareBouclier(arme)
      }
      if ( arme.system.totalDefensif > maxDef) {
        maxDef = arme.system.totalDefensif
        bestArme = foundry.utils.duplicate(arme)
      }
    }
    return bestArme
  }

  /* -------------------------------------------- */
  getCommonRollData(attrKey = undefined, compId = undefined, compName = undefined) {
    let rollData = WastelandUtility.getBasicRollData()
    rollData.alias = this.name
    rollData.actorImg = this.img
    rollData.actorId = this.id
    rollData.tokenId = this.token?.id
    rollData.img = this.img
    rollData.canEclatDoubleD20 = this.getEclat() >= 1 // Vérifier que l'acteur a au moins 1 point d'éclat
    rollData.doubleD20 = false
    rollData.attributs = WastelandUtility.getAttributs()
    rollData.config = foundry.utils.duplicate(game.system.wasteland.config)
    rollData.desavantages = {}
    rollData.isMonte = this.system.combat.monte

    if (attrKey) {
      rollData.attrKey = attrKey
      if (attrKey != "tochoose") {
        rollData.actionImg = "systems/fvtt-wasteland/assets/icons/" + this.system.attributs[attrKey].labelnorm + ".webp"
        rollData.attr = foundry.utils.duplicate(this.system.attributs[attrKey])
      }
    }
    if (compId) {
      rollData.competence = foundry.utils.duplicate(this.items.get(compId) || {})
      rollData.actionImg = rollData.competence?.img
    }
    if (compName) {
      rollData.competence = foundry.utils.duplicate(this.items.find( item => item.name.toLowerCase() == compName.toLowerCase()) || {})
      rollData.actionImg = rollData.competence?.img
    }
    return rollData
  }

  /* -------------------------------------------- */
  async launchRoll(rollData) {
    console.log("RollData", rollData)
    await WastelandRollDialog.create(this, rollData)
  }
  /* -------------------------------------------- */
  rollAttribut(attrKey) {
    let rollData = this.getCommonRollData(attrKey)
    this.launchRoll(rollData)
  }

  /* -------------------------------------------- */
  rollCompetence(attrKey, compId) {
    let rollData = this.getCommonRollData(attrKey, compId)
    console.log("RollDatra", rollData)
    this.launchRoll(rollData)
  }

  /* -------------------------------------------- */
  async rollCharme(charmeId) {
    let rollData = this.getCommonRollData("cla")
    rollData.charme = foundry.utils.duplicate(this.items.get(charmeId) || {})
    rollData.charmeDice = "1d4"
    this.launchRoll(rollData)
  }
  /* -------------------------------------------- */
  async rollPouvoir(pouvoirId) {
    let pouvoir = foundry.utils.duplicate(this.items.get(pouvoirId) || {})
    if (pouvoir?.system) {
      let rollData = this.getCommonRollData(pouvoir.system.attribut1, undefined, pouvoir.system.competence)
      if (!rollData.competence) {
        ui.notifications.error("Le pouvoir " + pouvoir.name + " n'a pas de compétence associée. Editez le pouvoir avec la compétence associée.")
        return
      }
      rollData.pouvoir = pouvoir
      rollData.difficulte = pouvoir.system.seuil
      this.launchRoll(rollData)
    }
  }
  /* -------------------------------------------- */
  async rollArmeOffensif(armeId) {
    let arme = this.items.get(armeId)
    if (arme.type == "arme") {
      arme = this.prepareArme(arme)
    }
    if (arme.type == "bouclier") {
      arme = this.prepareBouclier(arme)
    }
    let rollData = this.getCommonRollData(arme.system.attrKey, arme.system.competence._id)
    rollData.arme = arme
    rollData.typeAttaque = "assaut"
    rollData.typeCouvert = "aucun"
    rollData.hasDesavantageBonus = true
    rollData.visee = false
    rollData.ciblecourt = false
    rollData.cibleconsciente = false
    this.launchRoll(rollData)
  }

  /* -------------------------------------------- */
  async rollArmeDegats(armeId) {
    let arme = this.items.get(armeId)
    if (arme.type == "arme") {
      arme = this.prepareArme(arme)
    }
    if (arme.type == "bouclier") {
      arme = this.prepareBouclier(arme)
    }
    let roll = await new Roll(arme.system.totalDegats).roll()
    await WastelandUtility.showDiceSoNice(roll, game.settings.get("core", "rollMode"));
    let rollData = {
      arme: arme,
      finalResult: roll.total,
      alias: this.name,
      actorImg: this.img,
      actorId: this.id,
      actionImg: arme.img,
    }
    WastelandUtility.createChatWithRollMode(rollData.alias, {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-wasteland/templates/chat-degats-result-v2.hbs`, rollData)
    })

  }

  /* -------------------------------------------- */
  async rollAssommer() {
    let rollData = this.getCommonRollData("adr", undefined, "Mouvements")
    rollData.specialAction = "Assommer"
    rollData.typeAttaque = "assommer"
    rollData.typeCouvert = "aucun"
    rollData.hasDesavantageBonus = true
    if (rollData.defender) {
      rollData.selectDifficulte = false
      rollData.difficulte = rollData.defender.system.attributs.tre.value * 2
    }
    this.launchRoll(rollData)
  }

  /* -------------------------------------------- */
  async rollFuir() {
    let rollData = this.getCommonRollData("adr", undefined, "Mouvements")
    rollData.specialAction = "Fuir"
    rollData.typeAttaque = "fuir"
    rollData.typeCouvert = "aucun"
    rollData.hasDesavantageBonus = true
    if (rollData.defender) {
      rollData.selectDifficulte = false
      let comp = rollData.defender.items.find(it => it.type == "competence" && it.name.toLowerCase() == "mouvements")
      rollData.difficulte = rollData.defender.system.attributs.adr.value + ((comp) ? comp.system.niveau : rollData.defender.system.attributs.adr.value)
    }
    this.launchRoll(rollData)
  }

  /* -------------------------------------------- */
  async rollImmobiliser() {
    let rollData = this.getCommonRollData("pui", undefined, "Mêlée")
    rollData.specialAction = "Immobiliser"
    rollData.typeAttaque = "immobiliser"
    rollData.typeCouvert = "aucun"
    rollData.hasDesavantageBonus = true
    if (rollData.defender) {
      rollData.selectDifficulte = false
      rollData.difficulte = rollData.armeDefense ? rollData.armeDefense.system.totalDefensif : 10
    }
    this.launchRoll(rollData)
  }

}
