import { RdDItemSort } from "./item-sort.js";
import { Misc } from "./misc.js";
import { RdDResolutionTable } from "./rdd-resolution-table.js";

/**
 * Extend the base Dialog entity by defining a custom window to perform roll.
 * @extends {Dialog}
 */
export class RdDRollDialog extends Dialog {

  /* -------------------------------------------- */
  constructor(mode, html, rollData, actor, attacker = undefined) {

    let myButtons
    if (mode == "sort") {
      myButtons = {
        rollButton: { label: "Lancer le sort", callback: html => this.performRollSort(html, false) },
        reserveButton: { label: "Mettre en reserve", callback: html => this.performRollSort(html, true) }
      }
    }
    else {
      myButtons = {
        rollButton: { label: "Lancer", callback: html => this.actor.performRoll(this.rollData) }
      };
    }

    // Common conf
    let dialogConf = { content: html, title: "Test", buttons: myButtons, default: "rollButton" }
    let dialogOptions = { classes: ["rdddialog"], width: 600, height: 460, 'z-index': 99999 }
  
    // Select proper roll dialog template and stuff
    if (mode == "competence") {
      dialogConf.title = "Test de compétence"
      dialogOptions.height = 430
    } else if (mode == "arme") {
      dialogConf.title = "Test de combat/arme"
      dialogOptions.height = 460
    } else if (mode == "carac") {
      dialogConf.title = "Test de caractéristique"
      dialogOptions.height = 420
    } else if (mode == "sort") {
      dialogConf.title = "Lancer un sort"
      dialogOptions.height = 460
    }
    super(dialogConf, dialogOptions)

    this.mode = mode;
    this.rollData = rollData;
    this.actor = actor;
    if (attacker)
      this.attacker = attacker;
  }

  /* -------------------------------------------- */
  performRollSort(html, isSortReserve = false) {
    this.rollData.isSortReserve = isSortReserve;
    this.actor.performRoll(this.rollData, this.attacker);
  }

  /* -------------------------------------------- */
  activateListeners(html) {
    super.activateListeners(html);
    
    this.bringToTop(); // Ensure top level
    // Get the rollData stuff
    var rollData = this.rollData;

    function updateRollResult(rollData) {
      let caracValue = parseInt(rollData.selectedCarac.value)
      let rollLevel = RdDRollDialog._computeFinalLevel(rollData);

      rollData.finalLevel = rollLevel;
      rollData.caracValue = caracValue

      if (RdDRollDialog._isEtatGeneralApplicable(rollData)) {
        $(".etat-general").show();
      }
      else {
        $(".etat-general").hide();
      }
      // Sort management
      if ( rollData.selectedSort ) {
        //console.log("Toggle show/hide", rollData.selectedSort);
        if (RdDItemSort.isDifficulteVariable(rollData.selectedSort)) {
          $("#div-sort-difficulte").show();
        } else {
          $("#div-sort-difficulte").hide();
        }
        if (RdDItemSort.isCoutVariable(rollData.selectedSort)) {
          $("#div-sort-ptreve").show();
        } else {
          $("#div-sort-ptreve").hide();
        }
      }

      // Mise à jour valeurs
      $("#roll-param").text(rollData.selectedCarac.value + " / " + Misc.toSignedString(rollData.finalLevel));
      $("#compdialogTitle").text(RdDRollDialog._getTitle(rollData));
      $(".table-resolution").remove();
      $("#resolutionTable").append(RdDResolutionTable.buildHTMLTableExtract(caracValue, rollLevel));
    }

    // Setup everything onload
    $(function () {
      // Update html, according to data
      if (rollData.competence) {
        // Set the default carac from the competence item
        //console.log("RdDDialogRoll", rollData.competence.data.defaut_carac, rollData.carac);
        rollData.selectedCarac = rollData.carac[rollData.competence.data.defaut_carac];
        $("#carac").val(rollData.competence.data.defaut_carac);
      }
      RdDItemSort.setCoutReveReel(rollData.selectedSort);
      $("#diffLibre").val(Misc.toInt(rollData.diffLibre));
      $("#diffConditions").val(Misc.toInt(rollData.diffConditions));
      updateRollResult(rollData);
    });
    
    // Update !
    html.find('#diffLibre').change((event) => {
      rollData.diffLibre = Misc.toInt(event.currentTarget.value); // Update the selected bonus/malus
      //console.log("RdDRollDialog","BM CLICKED !!!", rollData);
      updateRollResult(rollData);
    });
    html.find('#diffConditions').change((event) => {
      rollData.diffConditions = Misc.toInt(event.currentTarget.value); // Update the selected bonus/malus
      //console.log("RdDRollDialog","BM CLICKED !!!", rollData);
      updateRollResult(rollData);
    });
    html.find('#carac').change((event) => {
      let caracKey = event.currentTarget.value;
      this.rollData.selectedCarac = rollData.carac[caracKey]; // Update the selectedCarac
      //console.log("RdDRollDialog","CARAC CLICKED !!!", rollData);
      updateRollResult(rollData);
    });
    html.find('#draconic').change((event) => {
      let draconicKey = Misc.toInt(event.currentTarget.value);
      this.rollData.selectedDraconic = rollData.draconicList[draconicKey]; // Update the selectedCarac
      //console.log("RdDRollDialog","CARAC CLICKED !!!", rollData);
      updateRollResult(rollData);
    });
    html.find('#sort').change((event) => {
      let sortKey = Misc.toInt(event.currentTarget.value);
      this.rollData.selectedSort = rollData.sortList[sortKey]; // Update the selectedCarac
      RdDItemSort.setCoutReveReel(rollData.selectedSort);
      //console.log("RdDRollDialog - Sort selection", rollData.selectedSort);
      updateRollResult(rollData);
    });
    html.find('#ptreve-variable').change((event) => {
      let ptreve = Misc.toInt(event.currentTarget.value);
      this.rollData.selectedSort.data.ptreve_reel = ptreve;
      console.log("RdDRollDialog - Cout reve", ptreve);
      updateRollResult(rollData);
    });
    html.find('#ptreve-variable').change((event) => {
      let ptreve = Misc.toInt(event.currentTarget.value);
      this.rollData.selectedSort.data.ptreve_reel = ptreve; // Update the selectedCarac
      console.log("RdDRollDialog - Cout reve", ptreve);
      updateRollResult(rollData);
    });
    html.find('#coupsNonMortels').change((event) => {
      this.rollData.mortalite = event.currentTarget.checked ? "non-mortel" : "non-mortel";
    });      
    html.find('#isCharge').change((event) => {
      this.rollData.isCharge = event.currentTarget.checked;
    });      
    html.find('#surencMalusApply').change((event) => {
      this.rollData.surencMalusApply = event.currentTarget.checked;
      updateRollResult(rollData);
    });      
    html.find('#useEncForNatation').change((event) => {
      this.rollData.useEncForNatation = event.currentTarget.checked;
      updateRollResult(rollData);
    });          
  }

  static _isEtatGeneralApplicable(rollData) {
    if (rollData.selectedCarac.label == 'Chance') return false;
    if (rollData.selectedCarac.label == 'Rêve Actuel') return false;
    
    return true;
  }

  /* -------------------------------------------- */
  static _computeFinalLevel(rollData) {
    const etat = RdDRollDialog._isEtatGeneralApplicable(rollData) ? Misc.toInt(rollData.etat) : 0;
    const diffConditions = Misc.toInt(rollData.diffConditions);
    let malusEnc  = (rollData.surencMalusApply ) ? rollData.surencMalusValue : 0;
    let diffLibre = Misc.toInt(rollData.diffLibre);
    let malusEncNatation = (rollData.useEncForNatation) ?  -rollData.encValueForNatation : 0;
    let chargeBonus = (rollData.isCharge) ? 4 : 0; // gestion de la charge en mélée

    // Gestion malus armure
    let malusArmureValue = 0;
    if ( rollData.malusArmureValue != 0 && (rollData.selectedCarac.label == "Agilité" || rollData.selectedCarac.label == "Dérobée" )) {
      $("#addon-message").text("Malus armure appliqué : " + rollData.malusArmureValue );
      malusArmureValue = rollData.malusArmureValue;
    } else  { 
      $("#addon-message").text("" );
    }

    let diffCompetence = 0;
    if (rollData.competence) {
      diffCompetence = Misc.toInt(rollData.competence.data.niveau);
    }
    else if (rollData.draconicList) {
      diffCompetence = Misc.toInt(rollData.selectedDraconic.data.niveau);
      diffLibre = RdDItemSort.getDifficulte(rollData.selectedSort, diffLibre);
    }

    return etat + diffCompetence + diffLibre + diffConditions + malusEnc + malusEncNatation + malusArmureValue + chargeBonus;
  }

  /* -------------------------------------------- */
  static _getTitle(rollData) {
    if (rollData.competence) {
      // If a weapon is there, add it in the title
      let armeTitle = (rollData.arme) ? " (" + rollData.arme.name + ") " : "";
      let niveau = Misc.toSignedString(rollData.competence.data.niveau);
      return rollData.selectedCarac.label + "/" + rollData.competence.name + armeTitle + " " + niveau
    }
    if (rollData.draconicList) {
      return rollData.selectedDraconic.name + " - " + rollData.selectedSort.name;
    }
    return rollData.selectedCarac.label;
  }
}
