
export class RdDInitiative {

  static PHASES = {
    possession: { key: 'possession', label: "possession", rang: 10 },
    draconic: { key: 'draconic', label: "draconic", rang: 9 },
    tir: { key: 'tir', label: "tir", rang: 8 },
    lancer: { key: 'lancer', label: "lancer", rang: 7 },
    arme: { key: 'arme', label: "mêlée", rang: 5 },
    pugilat: { key: 'pugilat', label: "pugilat", rang: 4 },
    naturelle: { key: 'naturelle', label: "créature", rang: 4 },
    empoignade: { key: 'empoignade', label: "empoignade", rang: 3 },
    autre: { key: 'autre', label: "autre action", rang: 2 },
    demi: { key: 'demi', label: "demi-surprise", rang: 0 },
    totale: { key: 'totale', label: "surprise totale", rang: -1 },
  }

  static phase(name) {
    if (Object.entries(this.PHASES).find(it => it[0] == name)) {
      return this.PHASES[name]
    }
    return this.PHASES.autre
  }

  static getRollInitiative(caracValue, niveau, bonus = 0) {
    const base = RdDInitiative.ajustementInitiative(caracValue, niveau, bonus)
    const addPlusSign = base >= 0 ? "+" : ""
    return `1d6${addPlusSign}${base}`
  }

  static ajustementInitiative(caracValue, niveau, bonus = 0) {
    return niveau + Math.floor(caracValue / 2) + bonus
  }

  static formule(phase, carac, niveau, bonusMalus = 0) {
    if (Object.keys(this.PHASES).find(it => it == phase)) {
      phase = this.PHASES[phase]
    }

    const ajustement = RdDInitiative.ajustementInitiative(carac, niveau, bonusMalus)
    return { phase, ajustement }
  }

  static phaseArme(categorie, arme) {
    switch (categorie) {
      case this.PHASES.tir.key:
      case this.PHASES.lancer.key:
        return this.PHASES[categorie]
      default:
        switch (arme.system.cac) {
          case this.PHASES.empoignade.key:
          case this.PHASES.pugilat.key:
          case this.PHASES.naturelle.key:
            return this.PHASES[arme.system.cac]
          default:
            return this.PHASES.arme
        }
    }
  }

  static phase(keyOrRang) {
    return this.PHASES[keyOrRang] ?? Object.values(this.PHASES).find(it => it.rang == keyOrRang) ?? this.PHASES.autre
  }

  static async roll(formule) {
    const sign = formule.ajustement >= 0 ? "+" : ""
    const roll = new Roll(`1d6 + ${sign} + ${formule.ajustement}`)
    await roll.evaluate()
    const value = Math.max(roll.total, 0)
    return {
      roll: roll,
      value: value,
      rang: formule.phase.rang,
      init: formule.phase.rang + value / 100,
      label: formule.phase.label
    }
  }
} 
