import { RdDActorSheetV2 } from "./personnage-sheet.mjs"
import { SYSTEM_RDD } from "../../constants.js"
import { Misc } from "../../misc.js"
import { EXPORT_CSV_SCRIPTARIUM, OptionsAvancees } from "../../settings/options-avancees.js"
import { ExportScriptarium } from "../../actor/export-scriptarium/export-scriptarium.js"
import { CATEGORIES_COMPETENCES_BASE, CATEGORIES_DRACONIC, Mapping } from "../../actor/export-scriptarium/mapping.js"

export class RdDActorExportSheetV2 extends RdDActorSheetV2 {

  static TYPE = "personnage"

  static DEFAULT_OPTIONS = Object.assign({}, RdDActorSheetV2.DEFAULT_OPTIONS, {
    position: { width: 550 },
  })

  static PARTS = {
    form: { template: "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/actor-encart-sheet.hbs" },
  }

  showCompNiveauBase = false
  vueArchetype = false

  static async init() {
    await foundry.applications.handlebars.loadTemplates([
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/arme.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/arme-titre.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/blessure.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/blessures.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/carac.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/carac-compteur.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/carac-derivee.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/carac-derivee-compteur.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/competences.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/esquive.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/fatigue.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/protection.hbs",
      "systems/foundryvtt-reve-de-dragon/templates/actor/export-scriptarium/sort.hbs",
    ])
  }

  static register() {
    foundry.documents.collections.Actors.registerSheet(SYSTEM_RDD, this, {
      types: ["personnage"],
      makeDefault: false,
      label: "Feuille simplifiée",
    })
  }

  async _prepareContext() {
    const ctx = await super._prepareContext()
    ctx.context = Mapping.prepareContext(this.actor)
    ctx.attaques = this.actor.listActionsAttaque()
    ctx.export = this._getMappingValues(ctx.context, this.actor)
    ctx.competences = this._getCompetences(CATEGORIES_COMPETENCES_BASE)
    ctx.draconic = this._getCompetences(CATEGORIES_DRACONIC)
    const legeres = this.actor.countBlessures(it => it.isLegere())
    const graves = this.actor.countBlessures(it => it.isGrave())
    const critiques = this.actor.countBlessures(it => it.isCritique())
    ctx.etat = {
      surenc: this.actor.computeMalusSurEncombrement(),
      fatigue: {
        value: this.actor.getFatigueActuelle(),
        max: this.actor.getFatigueMax(),
        malus: this.actor.malusFatigue(),
      },
      blessures: legeres + graves + critiques,
      blessure: [legeres > 0, legeres > 1, legeres > 2, legeres > 3, legeres > 4, graves > 0, graves > 1, critiques > 0],
    }
    ctx.options.exportScriptarium = OptionsAvancees.isUsing(EXPORT_CSV_SCRIPTARIUM)
    return ctx
  }

  _getMappingValues(context, actor) {
    return Object.fromEntries(Mapping.getMapping().map(it => [it.column, {
      colName: it.colName ?? it.column,
      column: it.column,
      rollClass: it.rollClass,
      value: String(it.getter(actor, context)),
    }]))
  }

  _getCompetences(categories) {
    const competences = Mapping.getCompetencesCategorie(this.actor, categories)
    if (competences.length == 0) return ""
    const byCategories = Mapping.competencesByCategoriesByNiveau(competences, categories)
    const listByCategories = Object.values(byCategories)
      .map(it => it.competencesParNiveau)
      .map(byNiveau => {
        const niveaux = Object.keys(byNiveau).map(it => Number(it)).sort(Misc.ascending())
        if (niveaux.length == 0) return undefined
        const listCategorieByNiveau = niveaux.map(niveau => {
          const list = byNiveau[niveau].sort(Misc.ascending(it => it.name))
          return { niveau, list }
        })
        return Misc.concat(listCategorieByNiveau)
      }).filter(it => it != undefined)
    return Misc.concat(listByCategories)
  }

  async _onRender(context, options) {
    await super._onRender(context, options)

    this.html.find(".click-blessure-remove").click(async event =>
      await this.actor.supprimerBlessure({
        gravite: this.html.find(event.currentTarget).data("gravite"),
      })
    )
    this.html.find(".click-blessure-add").click(async event => {
      const blessure = this.actor.nouvelleBlessure(this.html.find(event.currentTarget).data("gravite"))
      await this.actor.createEmbeddedDocuments("Item", [blessure])
    })
    this.html.find(".button-export").click(async event => await
      ExportScriptarium.INSTANCE.exportActors([this.actor],
        `${this.actor.uuid}-${this.actor.name}`
      )
    )
  }
}
