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

import { VadentisUtility } from "./vadentis-utility.js";

/* -------------------------------------------- */
export class VadentisActorSheet extends ActorSheet {

  /** @override */
  static get defaultOptions() {
    return mergeObject(super.defaultOptions, {
      classes: ["vadentis", "sheet", "actor"],
      template: "systems/foundryvtt-vadentis/templates/actor-sheet.html",
      width: 680,
      height: 720,
      tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "stats" }],
      dragDrop: [{ dragSelector: ".item-list .item", dropSelector: null }],
      editScore: false
    });
  }

  /* -------------------------------------------- */
  async getData() {
    this.actor.calculerSommeStats();

    let actorData = foundry.utils.duplicate(this.object.system);

    let formData = {
      title: this.title,
      id: this.object.id,
      type: this.object.type,
      img: this.object.img,
      name: this.object.name,
      editable: this.isEditable,
      cssClass: this.isEditable ? "editable" : "locked",
      data: actorData,
      effects: this.object.effects.map(e => foundry.utils.deepClone(e.data)),
      limited: this.object.limited,
      options: this.options,
      owner: this.document.isOwner,
      editScore: this.options.editScore,
      isGM: game.user.isGM,
      history: await TextEditor.enrichHTML(this.object.system.history, { async: true }),
      notes: await TextEditor.enrichHTML(this.object.system.notes, { async: true }),
      gmnotes: await TextEditor.enrichHTML(this.object.system.gmnotes, { async: true }),
    }

    formData.editScore = this.options.editScore;
    formData.donnees = this.actor.getDonnees();
    formData.eglises = this.actor.getEglises();
    formData.competences = this.actor.getCompetences();
    formData.sorts = this.actor.getSorts();
    formData.devotions = this.actor.getDevotions();
    formData.attributs = this.actor.getAttributs();
    formData.techniques = this.actor.getTechniques();
    formData.armes = this.actor.getArmes();
    formData.armures = this.actor.getArmures();
    formData.equipements = this.actor.getEquipements();
    formData.monnaies = this.actor.getMonnaies();

    formData.optionsBase = VadentisUtility.createDirectOptionList(0, 50);
    formData.optionsMalus = VadentisUtility.createDirectReverseOptionList(-50, 0);
    formData.optionsBonus = VadentisUtility.createDirectOptionList(0, 50);
    formData.optionsPV = VadentisUtility.createOptionList(-50, 999);
    formData.optionsPE = VadentisUtility.createOptionList(-50, 999);
    formData.optionsPA = VadentisUtility.createOptionList(0, 20);


    return formData;
  }

  /* -------------------------------------------- */
  async checkSort(sortId) {
    await Dialog.confirm({
      title: "Lancer un Sort",
      content: "Etes vous certain de vouloir incanter ce Sort ?",
      yes: async () => {
        this.actor.rollSort(sortId);
      },
      no: () => { },
    });
  }

  /* -------------------------------------------- */
  async checkDevotion(devotionId) {
    await Dialog.confirm({
      title: "Lancer une Dévotion",
      content: "Etes vous certain de vouloir incanter cette Dévotion ?",
      yes: async () => {
        this.actor.rollDevotion(devotionId);
      },
      no: () => { },
    });
  }

  /* -------------------------------------------- */
  async checkTechnique(techniqueId) {
    await Dialog.confirm({
      title: "Utiliser une technique",
      content: "Etes vous certain de vouloir utiliser cette Technique ?",
      yes: async () => {
        console.log("Technique  ", techniqueId)
        this.actor.rollTechnique(techniqueId);
      },
      no: () => { },
    });
  }

  /* -------------------------------------------- */
  /** @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");
      VadentisUtility.confirmDelete(this, li);
    });

    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");
      const item = this.actor.items.get(li.data("item-id"));
      this.actor.decrementeQuantite(item);
    });
    html.find('.equipement-plus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      const item = this.actor.items.get(li.data("item-id"));
      this.actor.incrementeQuantite(item);
    });

    html.find('.argent-moins').click(event => {
      const li = $(event.currentTarget).parents(".item");
      const item = this.actor.items.get(li.data("item-id"));
      this.actor.decrementeArgent(item);
    });
    html.find('.argent-plus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      const item = this.actor.items.get(li.data("item-id"));
      this.actor.incrementeArgent(item);
    });

    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-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const sortId = li.data("item-id");
      this.checkSort(sortId);
    });
    html.find('.arme-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const armeId = li.data("item-id");
      this.actor.rollArme(armeId);
    });
    html.find('.devotion-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const devotionId = li.data("item-id");
      this.checkDevotion(devotionId);
    });
    html.find('.weapon-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weapon = this.actor.items.get(li.data("item-id"));
      this.actor.rollWeapon(weapon);
    });
    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('.weapon-damage-critical').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weapon = this.actor.items.get(li.data("item-id"));
      this.actor.rollDamage(weapon, 'criticaldamage');
    });
    html.find('.sort-damage').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weapon = this.actor.items.get(li.data("item-id"));
      this.actor.rollSortDevotionDamage(weapon, 'damage');
    });
    html.find('.sort-damage-critical').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const weapon = this.actor.items.get(li.data("item-id"));
      this.actor.rollSortDevotionDamage(weapon, 'damagecritical');
    });

    html.find('.competence-base').change((event) => {
      let skillName = event.currentTarget.attributes.skillname.value;
      this.actor.updateCompetence(skillName, "base", parseInt(event.target.value));
    });
    html.find('.competence-bonus').change((event) => {
      let skillName = event.currentTarget.attributes.skillname.value;
      this.actor.updateCompetence(skillName, "bonus", parseInt(event.target.value));
    });
    html.find('.competence-malus').change((event) => {
      let skillName = event.currentTarget.attributes.skillname.value;
      this.actor.updateCompetence(skillName, "malus", 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);
  }
}
