/* -------------------------------------------- */
import { MournbladeUtility } from "./mournblade-utility.js";
import { MournbladeRollDialog } from "./mournblade-roll-dialog.js";

/* -------------------------------------------- */
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 MournbladeActor 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 == 'personnage') {
      const skills = await MournbladeUtility.loadCompendium("fvtt-mournblade.skills")
      data.items = skills.map(i => i.toObject())
    }
    if (data.type == 'pnj') {
    }

    return super.create(data, options);
  }

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

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

  /* -------------------------------------------- */
  getDons() {
    return this.data.items.filter(item => item.type == "don")
  }
  /* -------------------------------------------- */
  getTendances() {
    return this.data.items.filter(item => item.type == "tendance")
  }
  getRunes() {
    return this.data.items.filter(item => item.type == "rune")
  }
  /* -------------------------------------------- */
  getEquipments() {
    return this.data.items.filter(item => item.type == "equipement")
  }
  /* -------------------------------------------- */
  getArmors() {
    return this.data.items.filter(item => item.type == "protection")
  }
  getOrigine() {
    return this.data.items.find(item => item.type == "origine")
  }
  getMetier() {
    return this.data.items.find(item => item.type == "metier")
  }
  getHeritage() {
    return this.data.items.find(item => item.type == "heritage")
  }
  /* -------------------------------------------- */
  getSkills() {
    let comp = []
    for (let item of this.data.items) {
      item = duplicate(item)
      if (item.type == "competence") {
        item.data.attribut1total = item.data.niveau + (this.data.data.attributs[item.data.attribut1]?.value || 0)
        item.data.attribut2total = item.data.niveau + (this.data.data.attributs[item.data.attribut2]?.value || 0)
        item.data.attribut3total = item.data.niveau + (this.data.data.attributs[item.data.attribut3]?.value || 0)
        if (item.data.niveau == 0) {
          item.data.attribut1total -= 3
          item.data.attribut2total -= 3
          item.data.attribut3total -= 3
        }
        item.data.attribut1label = this.data.data.attributs[item.data.attribut1]?.label || ""
        item.data.attribut2label = this.data.data.attributs[item.data.attribut2]?.label || ""
        item.data.attribut3label = this.data.data.attributs[item.data.attribut3]?.label || ""
        comp.push(item)
      }
    }
    return comp.sort(function (a, b) {
      let fa = a.name.toLowerCase(),
        fb = b.name.toLowerCase();
      if (fa < fb) {
        return -1;
      }
      if (fa > fb) {
        return 1;
      }
      return 0;
    })
  }

  /* -------------------------------------------- */
  getAlignement() {
    return (this.data.data.balance.loi > this.data.data.balance.chaos) ? "loyal" : "chaotique"
  }

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

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

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

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

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

    if (this.type == 'personnage') {
      let newSante = this.data.data.sante.bonus + (this.data.data.attributs.pui.value + this.data.data.attributs.tre.value) * 2 + 5
      if (this.data.data.sante.base != newSante) {
        this.update({ 'data.sante.base': newSante })
      }
      let newAme = (this.data.data.attributs.cla.value + this.data.data.attributs.tre.value) * this.data.data.biodata.amemultiplier + 5
      if (this.data.data.ame.base != newAme) {
        this.update({ 'data.ame.base': newAme })
      }
    }

    super.prepareDerivedData()
  }

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

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

  /* -------------------------------------------- */
  getItemById(id) {
    let item = this.data.items.find(item => item.id == id);
    if (item) {
      item = duplicate(item)
    }
    return item;
  }

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

  /* -------------------------------------------- */
  editItemField(itemId, itemType, itemField, dataType, value) {
    let item = this.data.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, [`data.${itemField}`]: value };
      this.updateEmbeddedDocuments("Item", [update])
    }
  }

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

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

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

  /* -------------------------------------------- */
  changeEclat(value) {
    let newE = this.data.data.eclat.value
    newE += value
    this.update({ 'data.eclat.value': newE })
  }

  /* -------------------------------------------- */
  canEclatDoubleD20() {
    return (this.getAlignement() == "loyal" && this.data.data.eclat.value > 0)
  }

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

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

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

  /* -------------------------------------------- */
  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
    }
  }

  /* -------------------------------------------- */
  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 });
  }

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

  /* -------------------------------------------- */
  getCompetence(compId) {
    return this.data.items.get(compId)
  }

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

  /* -------------------------------------------- */
  getCommonRollData(attrKey = undefined, compId = undefined) {
    let rollData = MournbladeUtility.getBasicRollData()
    rollData.alias = this.name
    rollData.actorImg = this.img
    rollData.actorId = this.id
    rollData.img = this.img
    rollData.canEclatDoubleD20 = this.canEclatDoubleD20()
    rollData.doubleD20 = false
    rollData.attributs = MournbladeUtility.getAttributs()

    if (attrKey) {
      rollData.attrKey = attrKey
      if (attrKey != "tochoose") {
        rollData.actionImg = "systems/fvtt-mournblade/assets/icons/" + this.data.data.attributs[attrKey].labelnorm + ".webp"
        rollData.attr = duplicate(this.data.data.attributs[attrKey])
      }
    }
    if (compId) {
      rollData.competence = duplicate(this.data.items.get(compId) || {})
      rollData.actionImg = rollData.competence.img
    }
    return rollData
  }

  /* -------------------------------------------- */
  async rollAttribut(attrKey) {
    let rollData = this.getCommonRollData(attrKey)
    console.log("RollDatra", rollData)
    let rollDialog = await MournbladeRollDialog.create(this, rollData)
    rollDialog.render(true)
  }

  /* -------------------------------------------- */
  async rollCompetence(attrKey, compId) {
    let rollData = this.getCommonRollData(attrKey, compId)
    console.log("RollDatra", rollData)
    let rollDialog = await MournbladeRollDialog.create(this, rollData)
    rollDialog.render(true)
  }

  /* -------------------------------------------- */
  async rollArmeOffensif(armeId) {
    let arme = this.data.items.get(armeId)
    arme = this.prepareArme(arme)
    let rollData = this.getCommonRollData(arme.data.attrKey, arme.data.competence._id)
    rollData.arme = arme
    console.log("ARME!", rollData)
    let rollDialog = await MournbladeRollDialog.create(this, rollData)
    rollDialog.render(true)
  }

  /* -------------------------------------------- */
  async rollArmeDegats(armeId) {
    let arme = this.data.items.get(armeId)
    arme = this.prepareArme(arme)
    let roll = new Roll(arme.data.totalDegats).roll({ async: false })
    await MournbladeUtility.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,
    }
    MournbladeUtility.createChatWithRollMode(rollData.alias, {
      content: await renderTemplate(`systems/fvtt-mournblade/templates/chat-degats-result.html`, rollData)
    })

  }
}
