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

import { EcrymeUtility } from "../common/ecryme-utility.js";

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

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

    return {
      ...super.defaultOptions,
      classes: ["fvtt-ecryme", "sheet", "actor"],
      template: "systems/fvtt-ecryme/templates/actors/actor-sheet.hbs",
      width: 860,
      height:680,
      tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "skills" }],
      dragDrop: [{ dragSelector: ".item-list .item", dropSelector: null }],
      editScore: false
    };
  }

  /* -------------------------------------------- */
  async getData() {

    let formData = {
      title: this.title,
      id: this.actor.id,
      type: this.actor.type,
      img: this.actor.img,
      name: this.actor.name,
      editable: this.isEditable,
      cssClass: this.isEditable ? "editable" : "locked",
      system: foundry.utils.deepClone(this.object.system),
      limited: this.object.limited,
      skills: this.actor.prepareSkills(),
      traits: this.actor.getRollTraits(),
      confrontations: this.actor.getConfrontations(),
      ideal: this.actor.getIdeal(),
      spleen: this.actor.getSpleen(),
      impacts: this.object.getImpacts(),
      config: foundry.utils.deepClone(game.ecryme.config),
      weapons: this.actor.getWeapons(),
      maneuvers: this.actor.getManeuvers(),
      impactsMalus: this.actor.getImpactsMalus(),
      archetype: foundry.utils.deepClone(this.actor.getArchetype()),
      equipments: this.actor.getEquipments(),
      hasCephaly: EcrymeUtility.hasCephaly(),
      hasBoheme: EcrymeUtility.hasBoheme(),
      hasAmertume: EcrymeUtility.hasAmertume(),
      cephalySkills: this.actor.getCephalySkills(),
      subActors: foundry.utils.deepClone(this.actor.getSubActors()),
      annency: this.actor.getAnnency(),
      description: await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.object.system.biodata.description, { async: true }),
      notes: await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.object.system.biodata.notes, { async: true }),
      equipementlibre: await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.object.system.equipmentfree, { async: true }),
      options: this.options,
      owner: this.document.isOwner,
      editScore: this.options.editScore,
      isGM: game.user.isGM
    }
    this.formData = formData;

    //console.log("PC : ", formData, this.object);
    return formData;
  }


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

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

    html.bind("keydown", function(e) { // Ignore Enter in actores sheet
      if (e.keyCode === 13) return false;
    });

    html.find('.open-annency').click(ev => {
      let actorId = $(ev.currentTarget).data("annency-id")
      const actor = game.actors.get(actorId)
      actor.sheet.render(true)
    })

    // Update Inventory Item
    html.find('.item-edit').click(ev => {
      const li = $(ev.currentTarget).parents(".item")
      let itemId = li.data("item-id")
      if (!itemId) {
        itemId = $(ev.currentTarget).data("item-id")
      }
      const item = this.actor.items.get( itemId );
      item.sheet.render(true);
    });
    // Delete Inventory Item
    html.find('.item-delete').click(ev => {
      const li = $(ev.currentTarget).parents(".item")
      EcrymeUtility.confirmDelete(this, li).catch("Error : No deletion confirmed")
    })
    html.find('.item-add').click(ev => {
      let dataType = $(ev.currentTarget).data("type")
      this.actor.createEmbeddedDocuments('Item', [{ name: "NewItem", type: dataType }], { renderSheet: true })
    })

    html.find('.subactor-edit').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      let actorId = li.data("actor-id");
      let actor = game.actors.get( actorId );
      actor.sheet.render(true);
    });

    html.find('.subactor-delete').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      let actorId = li.data("actor-id");
      this.actor.delSubActor(actorId);
    });
    html.find('.quantity-minus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      this.actor.incDecQuantity( li.data("item-id"), -1 );
    } );
    html.find('.quantity-plus').click(event => {
      const li = $(event.currentTarget).parents(".item");
      this.actor.incDecQuantity( li.data("item-id"), +1 );
    } );

    html.find('.roll-skill').click((event) => {
      let categKey = $(event.currentTarget).data("category-key")
      let skillKey = $(event.currentTarget).data("skill-key")
      this.actor.rollSkill(categKey, skillKey)
    });
    html.find('.roll-spec').click((event) => {
      let categKey = $(event.currentTarget).data("category-key")
      let skillKey = $(event.currentTarget).data("skill-key")
      let specId = $(event.currentTarget).data("spec-id")
      this.actor.rollSpec(categKey, skillKey, specId)
    });
    html.find('.roll-skill-confront').click((event) => {
      let categKey = $(event.currentTarget).data("category-key")
      let skillKey = $(event.currentTarget).data("skill-key")
      this.actor.rollSkillConfront(categKey, skillKey)
    });
    html.find('.roll-cephaly').click((event) => {
      let skillKey = $(event.currentTarget).data("skill-key")
      this.actor.rollCephalySkillConfront(skillKey)
    });
    html.find('.roll-weapon-confront').click((event) => {
      const li = $(event.currentTarget).parents(".item")
      let weaponId = li.data("item-id");
      this.actor.rollWeaponConfront(weaponId)
    });

    html.find('.impact-modify').click((event) => {
      let impactType = $(event.currentTarget).data("impact-type")
      let impactLevel = $(event.currentTarget).data("impact-level")
      let modifier = Number($(event.currentTarget).data("impact-modifier"))
      this.actor.modifyImpact(impactType, impactLevel, modifier)
    });

    html.find('.roll-weapon').click((event) => {
      const armeId = $(event.currentTarget).data("arme-id")
      this.actor.rollWeapon(armeId)
    });

    html.find('.lock-unlock-sheet').click((event) => {
      this.options.editScore = !this.options.editScore;
      this.render(true);
    });
    html.find('.item-equip').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      this.actor.equipItem( li.data("item-id") );
      this.render(true);
    });
    html.find('.update-field').change(ev => {
      const fieldName = $(ev.currentTarget).data("field-name");
      let value = Number(ev.currentTarget.value);
      this.actor.update( { [`${fieldName}`]: value } );
    });
    html.find('.reset-transcendence').click(async (ev) => {
      await this.actor.resetSkillPool();
      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);
  }
}
