import { PegasusUtility } from "./pegasus-utility.js";

export class PegasusRollDialog extends Dialog {

  /* -------------------------------------------- */
  static async create(actor, rollData) {

    let options = { classes: ["PegasusDialog"], width: 620, height: 480, 'z-index': 99999 };
    let html = await renderTemplate('systems/fvtt-pegasus-rpg/templates/roll-dialog-generic.html', rollData);

    return new PegasusRollDialog(actor, rollData, html, options);
  }

  /* -------------------------------------------- */
  constructor(actor, rollData, html, options, close = undefined) {
    let conf = {
      title: (rollData.mode == "skill") ? "Skill" : "Roll",
      content: html,
      buttons: {
        roll: {
          icon: '<i class="fas fa-check"></i>',
          label: "Roll !",
          callback: () => { this.roll() }
        },
        cancel: {
          icon: '<i class="fas fa-times"></i>',
          label: "Cancel",
          callback: () => { this.close() }
        }
      },
      close: close
    }

    super(conf, options);

    this.actor = actor;
    this.rollData = rollData;
  }

  /* -------------------------------------------- */
  roll() {
    PegasusUtility.rollPegasus(this.rollData)
  }

  /* -------------------------------------------- */
  manageEffects(effectIdx, toggled) {
    let effect = this.rollData.effectsList[effectIdx]
    if (effect) {
      effect.applied = toggled

      let level, genre, idVal, key
      if (effect.type == 'effect') {
        let effectData = effect.effect
        level = effectData.data.effectlevel
        genre = effectData.data.genre
        effectData.data.isUsed = toggled
        if (effectData.data.reducedicevalue || effectData.data.statdice) {
          idVal = "#statDicesLevel"
          key = "statLevelBonus"
        }
      }
      // Now process the dice level update
      if (idVal) {
        let newLevel = Number($(idVal).val())
        if (toggled) {
          if (genre == 'positive') {
            newLevel += Number(level)
            this.rollData[key] += Number(level)
          } else {
            newLevel -= Number(level)
            this.rollData[key] -= Number(level)
          }
        } else {
          if (genre == 'positive') {
            newLevel -= Number(level)
            this.rollData[key] -= Number(level)
          } else {
            newLevel += Number(level)
            this.rollData[key] += Number(level)
          }
        }
        newLevel = (newLevel < 0) ? 0 : newLevel
        $(idVal).val(newLevel)
      }
    }
    //console.log("Effect", effect, toggled)  
    this.rollData.statDicesLevel = Number($('#statDicesLevel').val())
    //PegasusUtility.updateStatDicePool(this.rollData)
    PegasusUtility.updateSpecDicePool(this.rollData)
    PegasusUtility.updateDamageDicePool(this.rollData)
    PegasusUtility.updateEffectsBonusDice(this.rollData)
    PegasusUtility.updateHindranceBonusDice(this.rollData)
  }

  /* -------------------------------------------- */
  manageArmors(armorIdx, toggled) {
    let armor = this.rollData.armorsList[armorIdx]
    if (armor) {
      armor.applied = toggled
    }
    console.log("Armor", armorIdx, toggled)
    PegasusUtility.updateArmorDicePool(this.rollData)
  }

  /* -------------------------------------------- */
  manageWeapons(weaponIdx, toggled) {
    let weapon = this.rollData.weaponsList[weaponIdx]
    if (weapon) {
      if (toggled) {
        this.rollData.weaponName = weapon.weapon.name
      } else {
        this.rollData.weaponName = undefined
      }
      weapon.applied = toggled
    }
    console.log("Weapon", weaponIdx, toggled, weapon)
    PegasusUtility.updateDamageDicePool(this.rollData)
  }

  /* -------------------------------------------- */
  manageEquip(equipIdx, toggled) {
    let equip = this.rollData.equipmentsList[equipIdx]
    if (equip) {
      equip.applied = toggled
      let idVal = "#damageDiceLevel" // Default
      if (equip.equip.data.bonusdice) {
        idVal = "#bonusDicesLevel"
      }
      if (equip.equip.data.statdice) {
        idVal = "#statDicesLevel"
      }
      if (equip.equip.data.otherdice) {
        idVal = "#damageDiceLevel"
      }
      let newLevel = Number($(idVal).val())
      if (toggled) {
        newLevel += Number(equip.value)
      } else {
        newLevel -= Number(equip.value)
      }
      newLevel = (newLevel < 0) ? 0 : newLevel
      $(idVal).val(newLevel)
      // Then refresh
      this.rollData.statDicesLevel = Number($('#statDicesLevel').val())
      this.rollData.specDicesLevel = Number($('#specDicesLevel').val())
      this.rollData.bonusDicesLevel = Number($('#bonusDicesLevel').val())
      this.rollData.hindranceDicesLevel = Number($('#hindranceDicesLevel').val())
    }
  }

  /* -------------------------------------------- */
  async refreshDialog() {
    PegasusUtility.updateSpecDicePool(this.rollData)
    const content = await renderTemplate("systems/fvtt-pegasus-rpg/templates/roll-dialog-generic.html", this.rollData)
    this.data.content = content
    this.render(true)
  }

  /* -------------------------------------------- */
  activateListeners(html) {
    super.activateListeners(html);

    var dialog = this;
    function onLoad() {
    }
    $(function () { onLoad(); });

    html.find('#specList').change(async (event) => {
      this.rollData.selectedSpec = event.currentTarget.value
      let spec = this.rollData.specList.find(item => item._id == this.rollData.selectedSpec)
      if (spec) {
        this.rollData.specDicesLevel = spec.data.level
        this.rollData.specName = spec.name
        $('#specDicesLevel').val(this.rollData.specDicesLevel)
      } else {
        this.rollData.specName = undefined
        this.rollData.specDicesLevel = 0 
        $('#specDicesLevel').val(0)
      }
      PegasusUtility.updateSpecDicePool(this.rollData)
      this.refreshDialog()
    });
    html.find('#statDicesLevel').change((event) => {
      this.rollData.statDicesLevel = Number(event.currentTarget.value)
    });
    html.find('#specDicesLevel').change(async (event) => {
      if (event.currentTarget.value == "none") {
        this.rollData.specDicesLevel = 0  
      } else  {
        this.rollData.specDicesLevel = Number(event.currentTarget.value)
      }
      PegasusUtility.updateSpecDicePool(this.rollData)
      this.refreshDialog()
    });
    html.find('.effect-clicked').change(async (event) => {
      let toggled = event.currentTarget.checked
      let effectIdx = $(event.currentTarget).data("effect-idx")
      this.manageEffects(effectIdx, toggled)
      this.refreshDialog()
    });
    html.find('.armor-clicked').change((event) => {
      let toggled = event.currentTarget.checked
      let armorIdx = $(event.currentTarget).data("armor-idx")
      this.manageArmors(armorIdx, toggled)
      this.refreshDialog()
    });
    html.find('.weapon-clicked').change((event) => {
      let toggled = event.currentTarget.checked
      let weaponIdx = $(event.currentTarget).data("weapon-idx")
      this.manageWeapons(weaponIdx, toggled)
      this.refreshDialog()
    });
    html.find('.equip-clicked').change((event) => {
      let toggled = event.currentTarget.checked
      let equipIdx = $(event.currentTarget).data("equip-idx")
      this.manageEquip(equipIdx, toggled)
    })

    html.find('.pool-add-dice').click(async (event) => {
      let diceKey = $(event.currentTarget).data("dice-key")
      let diceLevel = $(event.currentTarget).data("dice-level")
      PegasusUtility.addDicePool(this.rollData, diceKey, diceLevel)
      this.refreshDialog()
    })
    html.find('.pool-remove-dice').click(async (event) => {
      let idx = $(event.currentTarget).data("dice-idx")
      PegasusUtility.removeFromDicePool(this.rollData, idx)
      this.refreshDialog()
    })


  }
}