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

import { SoSUtility } from "./sos-utility.js";

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

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

  /* -------------------------------------------- */
  getData() {
    const objectData = 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(this.object.system),
      effects: this.object.effects.map(e => foundry.utils.deepClone(e.data)),
      limited: this.object.limited,
      options: this.options,
      owner: this.document.isOwner
    };

    this.actor.checkDeck();

    formData.edgecard = this.actor.getEdgesCard();
    formData.deckSize = this.actor.getDeckSize();

    formData.skills   = this.actor.items.filter( item => item.type == 'skill').sort( (a, b) =>  { 
      if ( a.name > b.name ) return 1;
        return -1;
      });
    
    formData.skill1 = formData.skills.slice(0, Math.ceil(formData.skills.length/2) )
    formData.skill2 = formData.skills.slice(Math.ceil(formData.skills.length/2), formData.skills.length )
    formData.consequences = this.actor.items.filter( item => item.type == 'consequence').sort( (a, b) =>  { 
      if ( a.name > b.name ) return 1;
      return -1;
    });
    formData.gears  = this.actor.items.filter( item => item.type == 'gear').concat( this.actor.items.filter( item => item.type == 'container') );

    // Build the gear tree
    formData.gearsRoot = formData.gears.filter(item => item.system.containerid == "");
    for ( let container of formData.gearsRoot) {      
      if ( container.type == 'container') {
        container.data.contains = []
        container.data.containerEnc = 0;
        for (let gear of formData.gears) {
          console.log("GEAR", gear, container)
          if ( gear.system.containerid == container.id) {
            container.data.contains.push( gear )
            if ( !gear.system.neg && !gear.system.software ) {
              container.system.containerEnc += (gear.system.big > 0) ? gear.system.big : 1;
            }
          }
        }
      }
    }

    formData.weapons    = this.actor.items.filter( item => item.type == 'weapon');
    formData.armors     = this.actor.items.filter( item => item.type == 'armor');
    formData.totalEncumbrance = SoSUtility.computeEncumbrance(this.actor.items);
    formData.wounds     = duplicate(this.actor.system.wounds);
    formData.isGM       = game.user.isGM;
    formData.currentWounds = this.actor.computeCurrentWounds();
    formData.totalWounds = this.actor.system.scores.wound.value;

    formData.subcultureList = this.actor.items.filter( item => item.type == 'subculture');
    if ( formData.subculture != "" ) { // background.subculture contains the main subculture ID
      formData.mainSubculture = formData.subcultureList.find( subc => subc._id == this.actor.system.subculture);
    }
    formData.languageList  = this.actor.items.filter( item => item.type == 'language');
    formData.weaknessList  = this.actor.items.filter( item => item.type == 'weakness');
    formData.geneline      = this.actor.items.find( item => item.type == 'geneline');
    formData.editStatSkill =  this.options.editStatSkill;

    console.log("stats", formData);
    return formData;
  }

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

    //HtmlUtility._showControlWhen($(".gm-only"), game.user.isGM);

    // 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);
    });
    html.find('.item-equip').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      const item = this.actor.equipObject( li.data("item-id") );
      this.render(true);
    });
    html.find('.item-worn').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      const item = this.actor.wornObject( li.data("item-id") );
      this.render(true);
    });
    
    // Delete Inventory Item
    html.find('.item-delete').click(ev => {
      const li = $(ev.currentTarget).parents(".item");
      SoSUtility.confirmDelete(this, li);
    });

    html.find('.stat-label a').click((event) => {
      let statName = event.currentTarget.attributes.name.value;
      this.actor.rollStat(statName);
    });
    html.find('.skill-label a').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const skill = this.actor.items.get(li.data("item-id"));
      this.actor.rollSkill(skill);
    });
    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('.skill-value').change((event) => {
      let skillName = event.currentTarget.attributes.skillname.value;
      //console.log("Competence changed :", skillName);
      this.actor.updateSkill(skillName, parseInt(event.target.value));
    });
    html.find('.skill-xp').change((event) => {
      let skillName = event.currentTarget.attributes.skillname.value;
      //console.log("Competence changed :", skillName);
      this.actor.updateSkillExperience(skillName, parseInt(event.target.value));
    });
    html.find('.wound-value').change((event) => {
      let woundName = event.currentTarget.attributes.woundname.value;
      //console.log("Competence changed :", skillName);
      this.actor.updateWound(woundName, parseInt(event.target.value));
    });    
    html.find('.reset-deck-full').click((event) => {
      this.actor.resetDeckFull();
      this.render(true);
    });
    html.find('.draw-new-edge').click((event) => {
      this.actor.drawNewEdge();
      this.render(true);
    });
    html.find('.reset-deck').click((event) => {
      this.actor.resetDeck();
      this.render(true);
    });
    html.find('.discard-card').click((event) => {
      const cardName = $(event.currentTarget).data("discard");
      this.actor.discardEdge( cardName );
    });
    html.find('.consequence-severity').click((event) => {
      const li = $(event.currentTarget).parents(".item");
      const item = this.actor.items.get(li.data("item-id"));
      let severity = $(event.currentTarget).val();
      this.actor.updateEmbeddedDocuments( "Item", [ { _id: item.id, 'system.severity': severity} ] );
      this.render(true);
    });
    html.find('.lock-unlock-sheet').click((event) => {
      this.options.editStatSkill = !this.options.editStatSkill;
      this.render(true);
    });    
    html.find('.item-link a').click((event) => {
      const itemId = $(event.currentTarget).data("item-id");
      const item = this.actor.getOwnedItem(itemId);
      item.sheet.render(true);
    });    
    
  }

  /* -------------------------------------------- */
  async _onDrop(event) {
    let toSuper = await SoSUtility.processItemDropEvent(this, event);
    if ( toSuper) {
      super._onDrop(event);
    }
  }
  
  /* -------------------------------------------- */
  /** @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);
  }
}
