/**
 * Extend the basic ActorSheet with some very simple modifications
 * @extends {ActorSheet}
 */

import { RdDUtility } from "./rdd-utility.js";
import { RdDEncaisser } from "./rdd-roll-encaisser.js";
 
/* -------------------------------------------- */
export class RdDActorSheet extends ActorSheet {

  /** @override */
	static get defaultOptions() {
    RdDUtility.initAfficheContenu();
	  return mergeObject(super.defaultOptions, {
  	  classes: ["rdd", "sheet", "actor"],
  	  template: "systems/foundryvtt-reve-de-dragon/templates/actor-sheet.html",
      width: 640,
      //height: 720,
      tabs: [{navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "carac"}],
      dragDrop: [{dragSelector: ".item-list .item", dropSelector: null}],
      editCaracComp: false
    });
  }

  /* -------------------------------------------- */
  getData() {
    let data = super.getData();

    data.itemsByType = RdDUtility.buildItemsClassification(data.items);
    // Competence per category
    data.competenceByCategory = {};
    let competenceXPTotal = 0;
    if (data.itemsByType.competence) { 
      for (const item of data.itemsByType.competence) {
        //console.log("Push...", item, item.data.categorie);
        let list = data.competenceByCategory[item.data.categorie];
        if (!list) {
          list = [];
          data.competenceByCategory[item.data.categorie] = list;
        }
        if (!RdDUtility.isTronc( item.name ) ) // Ignorer les compétences 'troncs' à ce stade
          competenceXPTotal += RdDUtility.computeCompetenceXPCost(item)
        list.push(item);
      }
    }
    this.competenceByCategory = duplicate(data.competenceByCategory); // Sauvegarde locale
    competenceXPTotal += RdDUtility.computeCompetenceTroncXP(data.itemsByType.competence);
    data.data.competenceXPTotal = competenceXPTotal;
    //console.log("XP competence : ", competenceXPTotal);

    // Compute current carac sum
    let sum = 0;
    Object.values(data.data.carac).forEach(carac => { if (!carac.derivee) { sum += parseInt(carac.value) } } );
    data.data.caracSum = sum;

    // Force empty arme, at least for Esquive
    if (data.itemsByType.arme == undefined ) data.itemsByType.arme = [];
    for (const arme of data.itemsByType.arme) {      
      arme.data.niveau = 0; // Per default, TODO to be fixed
      for ( const melee of data.competenceByCategory.melee ) {
        if (melee.name == arme.data.competence ) 
          arme.data.niveau = melee.data.niveau
      }
      for ( const tir of data.competenceByCategory.tir ) {
        if (tir.name == arme.data.competence ) 
          arme.data.niveau = tir.data.niveau
      }
      for ( const lancer of data.competenceByCategory.lancer ) {
        if (lancer.name == arme.data.competence ) 
          arme.data.niveau = lancer.data.niveau
      }
    }

    // To avoid armour and so on...
    data.data.combat = duplicate( RdDUtility.checkNull(data.itemsByType['arme']));
    data.data.combat = RdDUtility.finalizeArmeList( data.data.combat, data.itemsByType.competence, data.data.carac );

    if (data.competenceByCategory && data.competenceByCategory.melee) { 
      //Specific case for Esquive and Corps à Corps
      for ( const melee of data.competenceByCategory.melee ) {
        if (melee.name == "Esquive")
          data.data.combat.push( { name: "Esquive", data: { niveau: melee.data.niveau, description: "", force: 6, initiative: "-", competence: "Esquive", dommages: 0} } );
        if (melee.name == "Corps à corps") {
          let cc_init = "1d6" + melee.data.niveau + "+" + Math.ceil(data.data.carac['melee'].value / 2 );
          data.data.combat.push( { name: "Corps à corps", data: { niveau: melee.data.niveau, description: "", force: 6, initiative: cc_init, competence: "Corps à corps", dommages: data.data.attributs.plusdom.value } } );
        }
      }
    }
    this.armesList = duplicate(data.data.combat);

    data.data.carac.taille.isTaille = true; // To avoid button link;
    data.data.nbLegeres   = this.actor.countBlessures(data.data.blessures.legeres.liste );
    data.data.nbGraves    = this.actor.countBlessures(data.data.blessures.graves.liste );
    data.data.nbCritiques = this.actor.countBlessures(data.data.blessures.critiques.liste );
    
    // Mise à jour de l'encombrement total
    this.actor.computeEncombrementTotalEtMalusArmure();
    // Common data
    data.data.competenceByCategory = data.competenceByCategory;
    data.data.encombrementTotal = this.actor.encombrementTotal;
    data.data.isGM = game.user.isGM;
    data.ajustementsConditions = CONFIG.RDD.ajustementsConditions;
    data.difficultesLibres = CONFIG.RDD.difficultesLibres;
    
    // Gestion du lock/unlock des zones éditables (carac+compétences)
    data.data.editCaracComp  = this.options.editCaracComp;
    data.data.lockUnlockText = (this.options.editCaracComp) ? "Bloquer" : "Débloquer";

    // low is normal, this the base used to compute the grid.
    data.data.fatigue = {
       malus: RdDUtility.calculMalusFatigue(data.data.sante.fatigue.value, data.data.sante.endurance.max),
       html: "<table class='table-fatigue'>" + RdDUtility.makeHTMLfatigueMatrix( data.data.sante.fatigue.value,  data.data.sante.endurance.max ).html() + "</table>"
      }
    
    RdDUtility.filterItemsPerTypeForSheet(data );
    data.data.sortReserve =  data.data.reve.reserve.list; 
    RdDUtility.buildArbreDeConteneur( this, data );
    data.data.surEncombrementMessage = (data.data.compteurs.surenc.value < 0) ? "Sur-Encombrement!" : "";

    return data;
  }
  
  /* -------------------------------------------- */
  async displayDialogEncaisser( ) {
    let data = { ajustementsEncaissement: RdDUtility.getAjustementsEncaissement() };
    let html = await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/dialog-roll-encaisser.html', data );
    new RdDEncaisser(html, this.actor ).render(true);
  }

  /* -------------------------------------------- */
  async _onDrop(event) {
    await RdDUtility.processItemDropEvent(this, event);
    super._onDrop(event);
  }

  /* -------------------------------------------- */
  async confirmerSuppression(li) {
    let itemId = li.data("item-id");
    let d = new Dialog({
      title: "Confirmer la suppression",
      content: "<p>Etes vous certain de vouloir supprimer cet objet ?</p>",
      buttons: {
        delete: {
          icon: '<i class="fas fa-check"></i>',
          label: "Supprimer",
          callback: () => { 
            console.log("Delete : ", itemId);
            this.actor.deleteOwnedItem(  itemId );
            li.slideUp(200, () => this.render(false));    
          }
        },
        cancel: {
          icon: '<i class="fas fa-times"></i>',
          label: "Annuler"
        }
      },
      default: "cancel",
    });
    d.render(true);
  }

  /* -------------------------------------------- */
  afficheResumeArchetype() {
    let levelCategory = RdDUtility.getLevelCategory();
    let labelCategory = RdDUtility.getLabelCategory();
    let contentHTML = "";
    for (let compCategory in this.competenceByCategory) {
      console.log(">>>>", compCategory);
      contentHTML += "<br><b>" + labelCategory[compCategory] + "</b>";
      for (let comp of this.competenceByCategory[compCategory]) {
        if ( !comp.data.niveau_archetype ) comp.data.niveau_archetype = levelCategory[compCategory];
        contentHTML += "<br>" + comp.name + " : " + comp.data.niveau_archetype;
      }
    }
    let dialogData = { 
      content: contentHTML, 
      buttons: {
        one: {
         icon: '<i class="fas fa-check"></i>',
         label: "Fermer"
        }
       }
    }
    new Dialog( dialogData ).render(true);
  }

  /* -------------------------------------------- */
  /** @override */
	activateListeners(html) {
    super.activateListeners(html);
    
    if (game.user.isGM) {
      $(".gm-only").show();
    } else {
      $(".gm-only").hide();
    }

    // Everything below here is only needed if the sheet is editable
    if (!this.options.editable) return;

    // Update Inventory Item
    html.find('.item-edit').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      const item = this.actor.getOwnedItem(li.data("item-id"));
      item.sheet.render(true);
    });
    
    // Delete Inventory Item
    html.find('.item-delete').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      this.confirmerSuppression( li );
    });

    html.find('#encaisser-direct').click(ev => {
      this.displayDialogEncaisser()
    });

    html.find('#remise-a-neuf').click(ev => {
      if (game.user.isGM) {
        this.actor.remiseANeuf();
      }
    });

    // Blessure control
    html.find('.blessure-control').click(ev => {
      const li   = $(ev.currentTarget).parents(".item");
      let btype  = li.data("blessure-type");
      let index  = li.data('blessure-index');
      let active = $(ev.currentTarget).data('blessure-active');
      //console.log(btype, index, active);
      this.actor.manageBlessureFromSheet(btype, index, active).then( this.render(true) );
    });

    // Blessure data
    html.find('.blessures-soins').change(ev => {
      const li   = $(ev.currentTarget).parents(".item");
      let btype  = li.data('blessure-type');
      let index  = li.data('blessure-index');
      let psoins    = li.find('input[name=premiers_soins]').val();
      let pcomplets = li.find('input[name=soins_complets]').val();
      let jours     = li.find('input[name=jours]').val();
      let loc       = li.find('input[name=localisation]').val();
      //console.log(btype, index, psoins, pcomplets, jours, loc);
      this.actor.setDataBlessureFromSheet(btype, index, psoins, pcomplets, jours, loc).then( this.render(true) );
    });

    // Equip Inventory Item
    html.find('.item-equip').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      this.actor.equiperObjet(li.data("item-id"));
      this.render(true);
    });

    // Roll Carac
    html.find('.carac-label a').click((event) => {
      let caracName = event.currentTarget.attributes.name.value;
      this.actor.rollCarac( caracName.toLowerCase() );
    });

    // Roll Skill
    html.find('.competence-label a').click((event) => {
      let compName = event.currentTarget.text;
      this.actor.rollCompetence( compName);
    });
    // Points de reve actuel
    html.find('.ptreve-actuel a').click((event) => {
      this.actor.rollCarac( 'reveActuel' );
    });    
    // Roll Weapon1
    html.find('.arme-label a').click((event) => {
      let armeName = event.currentTarget.text;
      let competenceName = event.currentTarget.attributes['data-competence-name'].value;
      this.actor.rollArme( armeName, competenceName);
    });
    // Initiative pour l'arme
    html.find('.arme-initiative a').click((event) => {
      let combatant = game.combat.data.combatants.find(c => c.actor.data._id == this.actor.data._id );
      if ( combatant ) {
        let armeName = event.currentTarget.attributes['data-arme-name'].value;
        let arme = this.armesList.find( a => a.name == armeName);
        RdDUtility.rollInitiativeCompetence( combatant._id, arme);
      } else {
        ui.notifications.info("Impossible de lancer l'initiative sans être dans un combat.");
      }
    });
    // Display TMR, normal
    html.find('#visu-tmr').click((event) => {
      this.actor.displayTMR( "visu");
    });

    // Display TMR, normal
    html.find('#monte-tmr').click((event) => {
      this.actor.displayTMR( "normal" );
    });
    
    // Display TMR, fast 
    html.find('#monte-tmr-rapide').click((event) => {
      this.actor.displayTMR( "rapide" );
    });

    html.find('#dormir-une-heure').click((event) => {
      this.actor.dormir(1);
    });
    html.find('#dormir-chateau-dormant').click((event) => {
      this.actor.dormirChateauDormant();
    });

    // Display info about queue
    html.find('.queuesouffle-label a').click((event) => {
      let myID = event.currentTarget.attributes['data-item-id'].value;
      const item = this.actor.getOwnedItem(myID);
      item.sheet.render(true);
    });
    // Display info about queue
    html.find('.sort-label a').click((event) => {
      let myID = event.currentTarget.attributes['data-id'].value;
      const item = this.actor.getOwnedItem(myID);
      item.sheet.render(true);
    });

    // Display info about queue
    html.find('.conteneur-name a').click((event) => {
      let myID = event.currentTarget.attributes['data-item-id'].value;
      RdDUtility.toggleAfficheContenu( myID );
      this.render(true);
    });
    
    if (this.options.editCaracComp) {
      // On carac change
      html.find('.carac-value').change((event) => {
        let caracName = event.currentTarget.name.replace(".value", "").replace("data.carac.", "");
        //console.log("Value changed :", event, caracName);
        this.actor.updateCarac( caracName, parseInt(event.target.value) );
      } );
      // On competence change
      html.find('.competence-value').change((event) => {
        let compName = event.currentTarget.attributes.compname.value;
        //console.log("Competence changed :", compName);
        this.actor.updateCompetence( compName, parseInt(event.target.value) );
      } );    
      // On competence xp change
      html.find('.competence-xp').change((event) => {
        let compName = event.currentTarget.attributes.compname.value;
        this.actor.updateCompetenceXP( compName, parseInt(event.target.value) );
      } );
    }

    // Gestion du bouton lock/unlock
    html.find('.lock-unlock-sheet a').click((event) => {
      this.options.editCaracComp = !this.options.editCaracComp;
      this.render(true);
    });
            
    // On pts de reve change
    html.find('.pointsreve-value').change((event) => {
      let reveValue = event.currentTarget.value;
      let reve = duplicate( this.actor.data.data.reve.reve );
      reve.value = reveValue;
      this.actor.update( { "data.reve.reve": reve } );
    } );
  
    // On seuil de reve change
    html.find('.seuil-reve-value').change((event) => {
      console.log("seuil-reve-value", event.currentTarget)
      this.actor.setPointsDeSeuil(event.currentTarget.value);
    } );

    // On stress change
    html.find('.compteur-edit').change((event) => {
      let fieldName = event.currentTarget.attributes.name.value;
      this.actor.updateCompteurValue( fieldName, parseInt(event.target.value) );
    } );
    
    // Dialog d'archetype
    html.find("#affiche-archetype").click((event) => {
      this.afficheResumeArchetype()
    } );

    html.find('#stress-test').click((event) => {
      this.actor.stressTest();
      this.render(true);
    });
    
    html.find('#vie-plus').click((event) => {
      this.actor.santeIncDec("vie", 1);
      this.render(true);
    });
    html.find('#vie-moins').click((event) => {
      this.actor.santeIncDec("vie", -1);
      this.render(true);
    });
    html.find('#endurance-plus').click((event) => {
      this.actor.santeIncDec("endurance", 1);
      this.render(true);
    });
    html.find('#endurance-moins').click((event) => {
      this.actor.santeIncDec("endurance", -1);
      this.render(true);
    });
    html.find('#ptreve-actuel-plus').click((event) => {
      this.actor.reveActuelIncDec(1);
      this.render(true);
    });
    html.find('#ptreve-actuel-moins').click((event) => {
      this.actor.reveActuelIncDec(-1);
      this.render(true);
    });
    html.find('#fatigue-plus').click((event) => {
      this.actor.santeIncDec("fatigue", 1);
      this.render(true);
    });
    html.find('#fatigue-moins').click((event) => {
      this.actor.santeIncDec("fatigue", -1);
      this.render(true);
    });
  }
  

  /* -------------------------------------------- */

  /** @override */
  setPosition(options={}) {
    const position = super.setPosition(options);
    const sheetBody = this.element.find(".sheet-body");
    const bodyHeight = position.height - 192;
    sheetBody.css("height", bodyHeight);
    return position;
  }


  /* -------------------------------------------- */

  /** @override */
  _updateObject(event, formData) {
    // Update the Actor
    return this.object.update(formData);
  }
}
