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

import { RdDUtility } from "./rdd-utility.js";
import { HtmlUtility } from "./html-utility.js";
import { Misc } from "./misc.js";
import { RdDSheetUtility } from "./rdd-sheet-utility.js";

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

  /** @override */
  static get defaultOptions() {
    RdDUtility.initAfficheContenu();

    return mergeObject(super.defaultOptions, {
      classes: ["rdd", "sheet", "actor"],
      template: "systems/foundryvtt-reve-de-dragon/templates/actor-vehicule-sheet.html",
      width: 640,
      height: 720,
      tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "carac" }],
      dragDrop: [{ dragSelector: ".item-list .item", dropSelector: null }]
    });
  }

  /* -------------------------------------------- */
  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.actor.system),
      effects: this.actor.effects.map(e => foundry.utils.deepClone(e)),
      limited: this.actor.limited,
      options: this.options,
      owner: this.actor.isOwner,
      itemsByType: Misc.classify(this.actor.items.map(i => foundry.utils.deepClone(i))),
    };

    RdDUtility.filterItemsPerTypeForSheet(formData);
    this.objetVersConteneur = RdDUtility.buildArbreDeConteneurs(formData.conteneurs, formData.objets);
    formData.conteneurs = RdDUtility.conteneursRacine(formData.conteneurs);

    formData.options.isGM = game.user.isGM;

    formData.calc = {
      encTotal: await this.actor.computeEncombrementTotalEtMalusArmure(),
      surEncombrementMessage: this.actor.getMessageSurEncombrement()
    }

    console.log("DATA", formData);

    return formData;
  }

  async computeMalusArmure() {
    // pas de malus armure
  }
  /* -------------------------------------------- */
  async _onDropItem(event, dragData) {
    const destItemId = $(event.target)?.closest('.item').attr('data-item-id');
    const dropParams = RdDSheetUtility.prepareItemDropParameters(destItemId, this.actor.id, dragData, this.objetVersConteneur);
    const callSuper = await this.actor.processDropItem(dropParams);
    if (callSuper) {
      await super._onDropItem(event, dragData)
    }
  }

  /* -------------------------------------------- */
  async createItem(name, type) {
    await this.actor.createEmbeddedDocuments('Item', [{ name: name, type: type }], { renderSheet: true });
  }

  /* -------------------------------------------- */
  async monnaieIncDec(id, value) {
    let monnaie = this.getMonnaie(id);
    if (monnaie) {
      const quantite = Math.max(0, monnaie.system.quantite + value);
      await this.updateEmbeddedDocuments('Item', [{ _id: monnaie.id, 'data.quantite': quantite }]);
    }
  }

  /* -------------------------------------------- */
  /** @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(async event => {
      const item = RdDSheetUtility.getItem(event, this.actor);
      item.sheet.render(true);
    });
    // Delete Inventory Item
    html.find('.item-delete').click(async event => {
      const li = RdDSheetUtility.getEventElement(event);
      const item = this.actor.getObjet(li.data("item-id"));
      RdDUtility.confirmerSuppressionItem(this, item, li);
    });
    html.find('.item-vendre').click(async event => {
      const item = RdDSheetUtility.getItem(event, this.actor);
      item?.proposerVente();
    });
    html.find('.item-montrer').click(async event => {
      const item = RdDSheetUtility.getItem(event, this.actor);
      item?.postItem();
    });

    html.find('.item-action').click(async event => {
      const item = RdDSheetUtility.getItem(event, this.actor);
      this.actor.actionItem(item);
    });

    html.find('.creer-un-objet').click(async event => {
      RdDUtility.selectObjetType(this);
    });
    html.find('#nettoyer-conteneurs').click(async event => {
      this.actor.nettoyerConteneurs();
    });

    html.find('.monnaie-plus').click(async event => {
      this.actor.monnaieIncDec(RdDSheetUtility.getItemId(event), 1);
    });
    html.find('.monnaie-moins').click(async event => {
      this.actor.monnaieIncDec(RdDSheetUtility.getItemId(event), -1);
    });

    // Display info about queue
    html.find('.conteneur-name a').click((event) => {
      RdDUtility.toggleAfficheContenu(RdDSheetUtility.getItemId(event));
      this.render(true);
    });

  }

  /* -------------------------------------------- */
  /** @override */
  setPosition(options = {}) {
    const position = super.setPosition(options);
    const sheetHeader = this.element.find(".sheet-header");
    const sheetTabs = this.element.find(".sheet-tabs");
    const sheetBody = this.element.find(".sheet-body");
    const bodyHeight = position.height - sheetHeader[0].clientHeight - sheetTabs[0].clientHeight;
    sheetBody.css("height", bodyHeight);
    return position;
  }


  /* -------------------------------------------- */
  /** @override */
  _updateObject(event, formData) {
    // Update the Actor
    return this.actor.update(formData);
  }
}
