import { Misc } from "./misc.js";
import { TMRUtility } from "./tmr-utility.js";

/* -------------------------------------------- */
export class RdDItemSort extends Item {

  /* -------------------------------------------- */
  static isDifficulteVariable(sort) {
    return sort && (sort.system.difficulte.toLowerCase() == "variable");
  }

  /* -------------------------------------------- */
  static isCoutVariable(sort) {
    return sort && (sort.system.ptreve.toLowerCase() == "variable" || sort.system.ptreve.indexOf("+") >= 0);
  }

  /* -------------------------------------------- */
  static setCoutReveReel(sort) {
    if (sort) {
      sort.system.ptreve_reel = this.isCoutVariable(sort) ? 1 : sort.system.ptreve;
    }
  }

  /* -------------------------------------------- */
  static getDifficulte(sort, variable) {
    if (sort && !RdDItemSort.isDifficulteVariable(sort)) {
      return Misc.toInt(sort.system.difficulte);
    }
    return variable;
  }

  /* -------------------------------------------- */
  static buildBonusCaseList(bonuscase, newCase) {
    const list = RdDItemSort._bonuscaseStringToList(bonuscase)
    if (newCase) {
      return list.concat({ case: "Nouvelle", bonus: 0 });
    }
    return list;
  }

  /**
   * Retourne une liste de bonus/case pour un item-sheet
  * @param {} item 
  */
  static getBonusCaseList(item, newCase = false) {
    // Gestion spéciale case bonus
    if (item.type == 'sort') {
      return RdDItemSort.buildBonusCaseList(item.system.bonuscase, newCase);
    }
    return undefined;
  }

  /* -------------------------------------------- */
  /** Met à jour les données de formulaire 
   * si static des bonus de cases sont présents 
   * */
  static buildBonuscaseFromArrays(bonuses, coords) {
    if (bonuses) {
      const list = [];
      const caseCheck = {};
      for (let i = 0; i < bonuses.length && i < coords.length; i++) {
        const coord = coords[i] == 'Fleuve' ? 'Fleuve' : (coords[i]?.toUpperCase() ?? 'A1');
        const bonus = bonuses[i] || 0;
        if (TMRUtility.verifyTMRCoord(coord) && bonus > 0 && caseCheck[coord] == undefined) {
          caseCheck[coord] = bonus;
          list.push({ case: coord, bonus: bonus });
        }
      }
      return RdDItemSort._bonuscaseListToString(list);
    }
    return undefined;
  }

  /* -------------------------------------------- */
  static incrementBonusCase(actor, sort, coord) {
    if (TMRUtility.getTMR(coord).type == "fleuve") {
      coord = 'Fleuve';
    }
    const list = RdDItemSort.buildBonusCaseList(sort.system.bonuscase, false);
    const bonus = Number(list.find(it => it.case == coord)?.bonus ?? 0);
    const modified = { case: coord, bonus: bonus + 1 };

    const bonuscase = RdDItemSort._bonuscaseListToString(
      list.filter(it => it.case != coord).concat(modified)
    );

    // Sauvegarde/update
    actor.updateEmbeddedDocuments('Item', [{ _id: sort._id, 'system.bonuscase': bonuscase }]);
  }


  /* -------------------------------------------- */
  static getCaseBonus(sort, coord) {
    const isFleuve = TMRUtility.getTMR(coord).type == "fleuve";

    let bc = RdDItemSort.buildBonusCaseList(sort.system.bonuscase, false)
      .filter(it => it.case == coord || (isFleuve && it.case == 'Fleuve'))
      .find(it => true)
    return Number(bc?.bonus ?? 0);
  }

  static _bonuscaseListToString(list) {
    return list.map(it => `${it.case}:${it.bonus}`)
      .sort(Misc.ascending())
      .join(',');
  }
  static _bonuscaseStringToList(bonuscase) {
    return (bonuscase ?? '').split(',').map(it => {
      const b = it.split(':');
      return { case: b[0], bonus: b[1] };
    });
  }

}