import { RdDItemCompetence } from "../item-competence.js"
import { RdDItemSort } from "../item-sort.js"
import { RdDResolutionTable } from "../rdd-resolution-table.js"
import { DIFF, ROLL_TYPE_SORT } from "./roll-constants.mjs"
import { PART_COMP } from "./roll-part-comp.mjs"
import { PART_SORT } from "./roll-part-sort.mjs"
import { RollType } from "./roll-type.mjs"

export class RollTypeSort extends RollType {
  get code() { return ROLL_TYPE_SORT }
  get name() { return `lancer un sort` }

  visible(rollData) { return rollData.active.actor.isHautRevant() }
  title(rollData) { return `lance le sort:` }

  onSelect(rollData) {
    this.setDiffType(rollData, DIFF.AUCUN)
  }

  getResult(rollData, impacts) {
    const rolled = rollData.rolled
    const actor = rollData.active.actor
    const coord = actor.system.reve.tmrpos.coord
    const reveActuel = parseInt(actor.system.reve.reve.value)
    const draconic = rollData.current[PART_COMP].comp

    const current = rollData.current[PART_SORT]
    const sort = current.sort
    const isReserve = current.isReserve
    const reveSort = current.ptreve
    const isThanatos = RdDItemCompetence.isThanatos(draconic)

    actor.tmrApp?.restoreTMRAfterAction()

    current.depenseReve = reveSort
    if (isThanatos) { // Si Thanatos
      impacts.addActorUpdate("system.reve.reve.thanatosused", true)
    }

    if (rolled.isSuccess) { // Réussite du sort !
      if (rolled.isPart) {
        current.depenseReve = Math.max(Math.floor(current.depenseReve / 2), 1)
      }
      if (isReserve) {
        current.depenseReve++
      }

      if (reveActuel > current.depenseReve) {
        // Incrémenter/gére le bonus de case
        impacts.addUpdate('Item', sort, 'system.bonuscase', RdDItemSort.calculBonuscase(sort, coord))

        if (isReserve) {
          impacts.addCreated('Item', RdDItemSort.prepareSortEnReserve(sort, draconic, reveSort, coord))
        }
        else {
          rollData.closeTMR = true
          if (sort.system.isrituel) {
            impacts.addUpdate('Item', sort, 'system.lancements', RdDItemSort.prepareSortAddLancement(sort, reveSort))
          }
        }
      }
      else {
        current.depenseReve = 0;
        rollData.show.reveInsuffisant = true
        foundry.utils.mergeObject(rollData.rolled, RdDResolutionTable.getResultat("echec"), { overwrite: true })
      }
    } else {
      rollData.closeTMR = true
      if (rolled.isETotal) { // Echec total !
        current.depenseReve = Math.min(reveActuel, Math.floor(current.depenseReve * 1.5))
        // TODO: mise en réserve d'un échec total...
      } else {
        current.depenseReve = 0
      }
    }
    
    impacts.addActorDelta("system.reve.reve.value", - Math.min(current.depenseReve, reveActuel))
    
    if (current.depenseReve >= reveActuel) { // 0 points de reve
      rollData.show.zeroReve = true
    }
  }

}