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

import { YggdrasillUtility } from "./yggdrasill-utility.js";

/* -------------------------------------------- */
export class YggdrasillActorSheet extends foundry.appv1.sheets.ActorSheet {

  /** @override */
  static get defaultOptions() {

    return foundry.utils.mergeObject(super.defaultOptions, {
      classes: ["yggdrasill", "sheet", "actor"],
      template: "systems/fvtt-yggdrasill/templates/actor-personnage-sheet.hbs",
      width: 680,
      height: 740,
      tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "stats" }],
      dragDrop: [{ dragSelector: ".item-list .item", dropSelector: null }],
      editScore: false
    });
  }

  /* -------------------------------------------- */
  async getData() {
    const objectData = foundry.utils.duplicate(this.object)

    let formData = {
      title: this.title,
      id: objectData.id,
      type: objectData.type,
      img: objectData.img,
      name: objectData.name,
      editable: this.isEditable,
      cssClass: this.isEditable ? "editable" : "locked",
      data: foundry.utils.deepClone(objectData.system),
      effects: this.object.effects.map(e => foundry.utils.deepClone(e.data)),
      limited: this.object.limited,
      isEpuise: this.actor.isEpuise(),
      isBlesse: this.actor.isBlesse(),
      isMeurtri: this.actor.isMeurtri(),
      competencesGenerales: this.actor.getCompetencesGenerales(),
      competencesMartiales: this.actor.getCompetencesMartiales(),
      competencesMagiques: this.actor.getCompetencesMagiques(),
      dons: this.actor.getDons(),
      faiblesses: this.actor.getFaiblesses(),
      blessures: this.actor.getBlessures(),
      armes: this.actor.getArmes(),
      armures: this.actor.getArmures(),
      boucliers: this.actor.getBoucliers(),
      prouessesMartiales: this.actor.getProuessesMartiales(),
      equipements: this.actor.getToutEquipements(),
      effetsmagiques: this.actor.getEffetsMagiques(),
      effetsRunes: this.actor.getEffetsDeRunes(),
      encTotal: this.actor.getEncTotal(),
      protectionTotal: this.actor.getProtectionTotal(),
      dpBouclier: this.actor.getDpBouclier(),
      monnaies: this.actor.getMonnaies(),
      sortsSejdr:this.actor.getSortsSejdr(),
      sortsGaldr:this.actor.getSortsGaldr(),
      runes: this.actor.getRunes(),
      optionsCarac: YggdrasillUtility.createDirectOptionList(0, 20),
      optionsDMDP: YggdrasillUtility.createDirectSortedOptionList(-10, +10),
      optionsBase: YggdrasillUtility.createDirectOptionList(0, 20),
      optionsFuror: YggdrasillUtility.createDirectOptionList(0, 15),
      tiragerunes:    await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.object.system.tiragesrunes, {async: true}),
      description:    await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.object.system.description, {async: true}),
      notes:    await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.object.system.notes, {async: true}),
      gmnotes: await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.object.system.biodata.gmnotes, {async: true}),
      options: this.options,
      owner: this.document.isOwner,
      editScore: this.options.editScore,
      isGM: game.user.isGM,
      config: game.system.config
    }
    // Dynamic update some fields
    this.updateDM(formData.data);
    this.updateDP(formData.data);

    console.log("YGG : ", formData);
    return formData;
  }

  /* -------------------------------------------- */
  updateDM( data ) {
    let dm = data.caracsecondaire.defensemen;
    dm.total = dm.max + Number(dm.bonusmalus);
  }
  /* -------------------------------------------- */
updateDP( data ) {
    let dp = data.caracsecondaire.defensephy;
    dp.total = dp.max + Number(dp.bonusmalus);
    dp.total += this.actor.getDpBouclier();
  }

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

    // 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.items.get(li.data("item-id"));
      item.sheet.render(true);
    });
    // Delete Inventory Item
    html.find('.item-delete').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      YggdrasillUtility.confirmDelete(this, li);
    });

    html.find('#isEpuise').click(event => {
      this.actor.toggleEpuise(  );
    } );

    html.find('.munition-moins').click(event => {
      const li = $(event.currentTarget).parents(".item");
      const item = this.actor.items.get(li.data("item-id"));
      this.actor.decrementeMunition( item );
    } );
    html.find('.munition-plus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      const item = this.actor.items.get(li.data("item-id"));
      this.actor.incrementeMunition( item );
    } );
    html.find('.equipement-moins').click(event => {
      const li = $(event.currentTarget).parents(".item");
      this.actor.decrementeQuantite( li.data("item-id") );
    } );
    html.find('.equipement-plus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      this.actor.incrementeQuantite( li.data("item-id") );
    } );

    html.find('.combat-label a').click((event) => {
      let combatName = event.currentTarget.attributes.name.value;
      this.actor.rollCombat(combatName);
    });
    html.find('.magie-label a').click((event) => {
      let magieName = event.currentTarget.attributes.name.value;
      this.actor.rollMagie(magieName);
    });
    html.find('.competence-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const competenceId = li.data("item-id");
      this.actor.rollCompetence(competenceId);
    });
    html.find('.technique-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const techniqueId = li.data("item-id");
      this.checkTechnique(techniqueId);
    });
    html.find('.sort-sejdr').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const sortId = li.data("item-id");
      this.actor.rollSort(sortId, "sejdr");
    });
    html.find('.sort-galdr').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const sortId = li.data("item-id");
      this.actor.rollSort(sortId, "galdr");
    });
    html.find('.sort-rune').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const sortId = li.data("item-id");
      this.actor.rollSort(sortId, "rune");
    });

    html.find('.arme-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const armeId = li.data("arme-id");
      this.actor.rollArme(armeId);
    });
    html.find('.carac-roll').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      let categ = li.data("carac-categ");
      let carac = li.data("carac-key");
      this.actor.rollCarac(categ, carac);
    });
    html.find('.weapon-damage').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weapon = this.actor.items.get(li.data("item-id"));
      this.actor.rollDamage(weapon, 'damage');
    });
    html.find('.competence-base').change((event) => {
      const li = $(event.currentTarget).parents(".item");
      const compId = li.data("item-id");
      this.actor.updateCompetence(compId, parseInt(event.target.value));
    });
    html.find('.lock-unlock-sheet').click((event) => {
      this.options.editScore = !this.options.editScore;
      this.render(true);
    });
    html.find('.item-link a').click((event) => {
      const itemId = $(event.currentTarget).data("item-id");
      const item = this.actor.items.get(itemId);
      item.sheet.render(true);
    });
    html.find('.item-equip').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      this.actor.equiperObject( li.data("item-id") );
      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);
  }
}
