import { HtmlUtility } from "../html-utility.js";
import { RdDItemSheet } from "../item-sheet.js";
import { Misc } from "../misc.js";
import { RdDRaretes } from "./raretes.js";

const TYPE_ITEMS_NATURELS = ["faune", "herbe", "plante", "ingredient"];

export class RdDItemInventaireSheet extends RdDItemSheet {

  static get defaultOptions() {
    return mergeObject(RdDItemSheet.defaultOptions, {
      tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "informations" }]
    });
  }

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

  async getData() {
    const formData = await super.getData();
    return mergeObject(formData, {
      milieux: await game.system.rdd.environnement.autresMilieux(this.item)
    });
  }

  activateListeners(html) {
    super.activateListeners(html);
    HtmlUtility.showControlWhen(this.html.find("div.description-milieu"), TYPE_ITEMS_NATURELS.includes(this.item.type));

    if (!this.options.editable) return;
    this.html.find("a.preparer-nourriture").click(event => this.preparerNourriture(event));
    this.html.find("a.manger-nourriture").click(event => this.mangerNourriture(event));

    this.html.find("input.input-selection-milieu").keypress(event => {
      if (event.keyCode == '13') {
        this.onAddMilieu(event);
      }
      event.stopPropagation();
    })
    this.html.find("a.milieu-add").click(event => this.onAddMilieu(event));
    this.html.find("div.environnement-milieu a.milieu-delete").click(event => this.onDeleteMilieu(event));
    this.html.find("div.environnement-milieu select.environnement-rarete").change(event => this.onChange(event,
      updated => this.$changeRarete(event, updated)));
    this.html.find("div.environnement-milieu input[name='environnement-frequence']").change(event => this.onChange(event,
      updated => this.$changeFrequence(event, updated)));


  }

  async preparerNourriture(event) {
    if (this.actor && this.item.getUtilisationCuisine() == 'brut') {
      await this.actor.preparerNourriture(this.item);
    }
  }

  async mangerNourriture(event) {
    if (this.actor && this.item.getUtilisation() == 'cuisine') {
      await this.actor.mangerNourriture(this.item);
    }
  }

  $changeFrequence(event, updated) {
    updated.frequence = Number(this.html.find(event.currentTarget).val());
  }

  $changeRarete(event, updated) {
    const code = this.html.find(event.currentTarget).val();
    const rarete = RdDRaretes.byCode(code);
    updated.rarete = rarete.code;
    updated.frequence = rarete.frequence;
  }

  async onAddMilieu(event) {
    const milieu = this.html.find('input.input-selection-milieu').val();
    if (!milieu) {
      ui.notifications.warn(`Choisissez le milieu dans lequel se trouve le/la ${this.item.name}`);
      return
    }
    const list = this.item.getEnvironnements();
    const exists = list.find(it => it.milieu == milieu);
    if (exists) {
      ui.notifications.warn(`${this.item.name} a déjà une rareté ${exists.rarete} en ${milieu} (fréquence: ${exists.frequence})`);
      return
    }
    const rarete = RdDRaretes.rareteFrequente();
    const added = { milieu, rarete: rarete.code, frequence: rarete.frequence };
    const newList = [added, ...list].sort(Misc.ascending(it => it.milieu))
    await this.item.update({ 'system.environnement': newList })
  }

  async onDeleteMilieu(event) {
    const milieu = this.$getEventMilieu(event);
    if (milieu != undefined) {
      const newList = this.item.getEnvironnements().filter(it => it.milieu != milieu)
        .sort(Misc.ascending(it => it.milieu));
      await this.item.update({ 'system.environnement': newList });
    }
  }

  async onChange(event, doMutation) {
    const list = this.item.system.environnement;
    const milieu = this.$getEventMilieu(event);
    const updated = list.find(it => it.milieu == milieu);
    if (updated) {
      doMutation(updated);
      const newList = [...list.filter(it => it.milieu != milieu), updated]
        .sort(Misc.ascending(it => it.milieu));
      await this.item.update({ 'system.environnement': newList });
    }
  }

  $getEventMilieu(event) {
    return this.html.find(event.currentTarget)?.parents("div.environnement-milieu").data("milieu");
  }
}
