import { TYPES } from "../item.js"
import { RdDItemCompetence } from "../item-competence.js"
import { ChatUtility } from "../chat-utility.js"

const CODES_COMPETENCES_VOYAGE = ['Extérieur', 'Forêt', 'Montagne', 'Marais', 'Glace', 'Equitation']
const TABLEAU_FATIGUE_MARCHE = [
  {
    code: "aise", label: "Aisé", description: "Route ou chemin",
    survies: ['Extérieur', 'Equitation'],
    vitesses: [{ vitesse: 4, fatigue: 1 }, { vitesse: 6, fatigue: 2 }, { vitesse: 8, fatigue: 3 }, { vitesse: 10, fatigue: 4 }, { vitesse: 12, fatigue: 6 }],
  },
  {
    code: "malaise", label: "Malaisé", description: "Hors piste (herbes et buissons)",
    survies: ['Extérieur', 'Equitation'],
    vitesses: [{ vitesse: 4, fatigue: 2 }, { vitesse: 6, fatigue: 3 }, { vitesse: 8, fatigue: 4 }, { vitesse: 10, fatigue: 6 }],
  },
  {
    code: "difficile", label: "Difficile", description: "Hors piste (collines, forêt)",
    survies: ['Extérieur', 'Forêt', 'Glace', 'Equitation'],
    vitesses: [{ vitesse: 4, fatigue: 3 }, { vitesse: 6, fatigue: 4 }, { vitesse: 8, fatigue: 6 }],
  },
  {
    code: "tresdifficile", label: "Très difficile", description: "Hors piste (montagne, jungle, marais)",
    survies: ['Forêt', 'Montagne', 'Marais', 'Glace'],
    vitesses: [{ vitesse: 4, fatigue: 4 }, { vitesse: 6, fatigue: 6 }],
  },
]

export class DialogFatigueVoyage extends Dialog {
  static dialog = undefined
  static async create() {
    if (!game.user.isGM) {
      return
    }
    if (!DialogFatigueVoyage.dialog) {
      const playerActors = game.actors.filter(actor => actor.hasPlayerOwner && actor.isPersonnage())
        .map(actor => DialogFatigueVoyage.prepareActor(actor))
      const parameters = {
        tableauFatigueMarche: TABLEAU_FATIGUE_MARCHE,
        playerActors: playerActors,
        nombreHeures: 1,
      }
      DialogFatigueVoyage.setModeDeplacement(parameters, undefined, undefined)

      const html = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/voyage/dialog-fatigue-voyage.hbs", parameters);
      DialogFatigueVoyage.dialog = new DialogFatigueVoyage(html, parameters);
    }
    DialogFatigueVoyage.dialog.render(true);
  }

  static setModeDeplacement(parameters, code, vitesse) {
    const ligneFatigueMarche = TABLEAU_FATIGUE_MARCHE.find(it => it.code == code) ?? TABLEAU_FATIGUE_MARCHE[0]
    const rythme = ligneFatigueMarche.vitesses.find(it => it.vitesse == vitesse) ?? ligneFatigueMarche.vitesses[0]
    parameters.typeTerrain = ligneFatigueMarche
    parameters.vitesseDeplacement = rythme.vitesse
    parameters.fatigueHoraire = rythme.fatigue
  }

  static prepareActor(actor) {
    const competencesVoyage = {}
    CODES_COMPETENCES_VOYAGE.forEach(codeSurvie =>
      competencesVoyage[codeSurvie] = RdDItemCompetence.findCompetence(actor.itemTypes[TYPES.competence], codeSurvie, { onMessage: () => { } })
    )
    return {
      actor: actor,
      selected: true,
      ajustementFatigue: 0,
      competencesVoyage: competencesVoyage
    }
  }


  constructor(html, parameters) {
    const options = {
      classes: ["dialog-fatigue-voyage"],
      width: 600,
      height: 'fit-content',
      'max-height': 900,
      'z-index': 99999
    }
    const conf = {
      title: "Fatigue de voyage",
      content: html,
      buttons: {}
    }
    super(conf, options);
    this.parameters = parameters
    this.controls = {}
  }

  activateListeners(html) {
    if (this.html == undefined) {
      html.find('select[name="code-terrain"]').trigger("focus")
    }
    this.html = html;
    super.activateListeners(html);

    this.html.find('select[name="code-terrain"]').change(event => this.changeParameters())
    this.html.find('select[name="vitesse-deplacement"]').change(event => this.changeParameters())
    this.html.find('input[name="nombre-heures"]').change(event => this.changeParameters())
    this.html.find('button[name="appliquer-fatigue"]').click(event => this.appliquerFatigue())
  }

  changeParameters() {
    this.changeTerrain(this.html.find('select[name="code-terrain"]').val())
    this.changeVitesse(this.html.find('select[name="vitesse-deplacement"]').val())
    this.changeNombreHeures(this.html.find('input[name="nombre-heures"]').val())
    this.setFatigue()
  }

  async changeTerrain(codeTerrain) {
    if (this.parameters.typeTerrain.code != codeTerrain) {
      const selectVitesseDeplacement = this.html.find('select[name="vitesse-deplacement"]')
      const vitesse = selectVitesseDeplacement.val()
      selectVitesseDeplacement.empty()

      DialogFatigueVoyage.setModeDeplacement(this.parameters, codeTerrain, vitesse)
      this.parameters.typeTerrain.vitesses.forEach(async rythme => {
        selectVitesseDeplacement.append(await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/voyage/option-vitesse-fatigue.hbs', rythme))
      })
      selectVitesseDeplacement.val(this.parameters.vitesseDeplacement).change()
    }
  }

  async changeVitesse(vitesse) {
    if (this.parameters.vitesseDeplacement != vitesse) {
      DialogFatigueVoyage.setModeDeplacement(this.parameters, this.parameters.typeTerrain.code, vitesse)
    }
  }

  async changeNombreHeures(nombreHeures) {
    this.parameters.nombreHeures = parseInt(nombreHeures)
  }

  async setFatigue() {
    this.html.find('input[name="base-fatigue"]').val(this.parameters.nombreHeures * this.parameters.fatigueHoraire)
  }

  async appliquerFatigue() {
    const fatigueBase = parseInt(this.html.find('input[name="base-fatigue"]').val() ?? 0)
    const actors = jQuery.map(
      this.html.find('div.fatigue-actors-list li.list-item'),
      it => this.$extractActor(this.html.find(it))
    )
    actors.filter(it => it.selected)
    .forEach(async it => {
        const perteFatigue = fatigueBase + it.ajustement
        ChatMessage.create({
          whisper: ChatUtility.getWhisperRecipientsAndGMs(it.actor.name),
          content: await renderTemplate(
            'systems/foundryvtt-reve-de-dragon/templates/voyage/chat-fatigue_voyage.hbs', mergeObject(it,
              {
                parameters: this.parameters,
                fatigueBase: fatigueBase,
                perteFatigue: perteFatigue,
                isVoyage: fatigueBase == this.parameters.nombreHeures * this.parameters.fatigueHoraire
              })
          ),
        })
        await it.actor.santeIncDec("fatigue", perteFatigue)
      })
  }

  $extractActor(actorRow) {
    const actor = game.actors.get(actorRow.data('actor-id'))
    if (!actor) {
      ui.notifications.warn(`Acteur ${it.actorId} introuvable`)
    }
    return {
      actor: actor,
      ajustement: parseInt(actorRow.find('input[name="ajustement-fatigue"]').val() ?? 0),
      selected: actor && actorRow.find('input[name="selectionner-acteur"]').is(':checked')
    }
  }

  async close() {
    DialogFatigueVoyage.dialog = undefined
    await super.close()
  }


}