import { RdDItemSort } from "./item-sort.js";
import { RdDUtility } from "./rdd-utility.js";
import { RdDItem } from "./item-rdd.js";
import { RdDAlchimie } from "./rdd-alchimie.js";
import { RdDItemCompetence } from "./item-competence.js";
import { Misc } from "./misc.js";

/**
 * Extend the basic ItemSheet with some very simple modifications
 * @extends {ItemSheet}
 */
export class RdDItemSheet extends ItemSheet {

  /** @override */
	static get defaultOptions() {
	  return mergeObject(super.defaultOptions, {
			classes: ["foundryvtt-reve-de-dragon", "sheet", "item"],
			template: "systems/foundryvtt-reve-de-dragon/templates/item-sheet.html",
			width: 550,
			height: 550
      //tabs: [{navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "description"}]
		});
  }

  /* -------------------------------------------- */
  _getHeaderButtons() {
    let buttons = super._getHeaderButtons();
    // Add "Post to chat" button
    // We previously restricted this to GM and editable items only. If you ever find this comment because it broke something: eh, sorry!
    buttons.unshift(
      {
        class: "post",
        icon: "fas fa-comment",
        onclick: ev => new RdDItem(Misc.data(this.item)).postItem()
      })
    return buttons
  }

  /* -------------------------------------------- */
  /** @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;
  }
  
  /* -------------------------------------------- */
  async getData() {
    let formData = super.getData();
    formData.categorieCompetences = RdDItemCompetence.getCategorieCompetences();
    if ( formData.item.type == 'tache' || formData.item.type == 'livre' || formData.item.type == 'meditation' || formData.item.type == 'oeuvre') {
      formData.caracList = duplicate(game.system.model.Actor.personnage.carac);
      formData.competences = await RdDUtility.loadCompendiumNames( 'foundryvtt-reve-de-dragon.competences' );
    }
    if (formData.item.type == 'arme') {
      formData.competences = await RdDUtility.loadCompendium( 'foundryvtt-reve-de-dragon.competences', it => RdDItemCompetence.isCompetenceArme(it));
    }
    if ( formData.item.type == 'recettealchimique' ) {
      RdDAlchimie.processManipulation(formData.item, this.actor && this.actor._id );
    }
    if ( this.actor ) {
      formData.isOwned = true;
      formData.actorId = this.actor._id;
    }
    formData.bonusCaseList = RdDItemSort.getBonusCaseList(formData, true);
    formData.isGM = game.user.isGM; // Pour verrouiller certaines éditions

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

    // Everything below here is only needed if the sheet is editable
    if (!this.options.editable) return;
    
    // Select competence categorie
    html.find("#categorie").on("click", this._onClickSelectCategorie.bind(this) );

    html.find('#sheet-competence-xp').change((event) => {
      if ( this.object.data.type == 'competence') { 
        RdDUtility.checkThanatosXP( this.object.data.name );
      }
    } );

    html.find('#creer-tache-livre').click((event) => {
      let actorId = event.currentTarget.attributes['data-actor-id'].value;
      let actor = game.actors.get( actorId );
      actor.creerTacheDepuisLivre( this.item );
    });

    html.find('.alchimie-tache a').click((event) => {
      let actorId = event.currentTarget.attributes['data-actor-id'].value;
      let recetteId = event.currentTarget.attributes['data-recette-id'].value;
      let tacheName = event.currentTarget.attributes['data-alchimie-tache'].value;
      let tacheData = event.currentTarget.attributes['data-alchimie-data'].value;
      let actor = game.actors.get( actorId );
      if ( actor ) {
        actor.effectuerTacheAlchimie(recetteId, tacheName, tacheData);
      } else {
        ui.notifications.info("Impossible trouver un actur pour réaliser cette tache Alchimique.");
      }
    });
    
  }
  
  /* -------------------------------------------- */
  async _onClickSelectCategorie(event) {
    event.preventDefault();
    
    let level = RdDItemCompetence.getNiveauBase(event.currentTarget.value);    
    this.object.data.data.base = level;
    $("#base").val( level ); 
  }

  /* -------------------------------------------- */
  get template()
  {
    let type = this.item.type;
    return `systems/foundryvtt-reve-de-dragon/templates/item-${type}-sheet.html`;
  }

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

  /** @override */
  _updateObject(event, formData) {
    // Données de bonus de cases ?
    formData = RdDItemSort.buildBonusCaseStringFromFormData( formData );
    
    return this.object.update(formData);
  }
}
