import { SYSTEM_RDD } from "./constants.js";
import { Grammar } from "./grammar.js";
import { Misc } from "./misc.js";
import { CompendiumTableHelpers, CompendiumTable, SystemCompendiums } from "./settings/system-compendiums.js";


const COMPENDIUMS_RECHERCHE = 'compendiums-recherche';

export class Environnement {
  static initSettings() {
    game.settings.register(SYSTEM_RDD, COMPENDIUMS_RECHERCHE, {
      name: COMPENDIUMS_RECHERCHE,
      default: [
        SystemCompendiums.getCompendium('faune-flore-mineraux'),
        SystemCompendiums.getCompendium('meditations-et-ecrits'),
        SystemCompendiums.getCompendium('equipement')
      ],
      scope: "world",
      config: false,
      type: Object
    });

    game.system.rdd.environnement = new Environnement();
    Hooks.once('ready', () => game.system.rdd.environnement.onReady());
  }

  constructor() {
    this.compendiums = [];
    this.compendiumTables = [];
    this.mapMilieux = {}
  }

  async onReady() {
    await this.$prepareCompendiums()
  }

  async milieux() {
    return Object.values(this.mapMilieux);
  }

  async saveCompendiums(compendiumIds) {
    game.settings.set(SYSTEM_RDD, COMPENDIUMS_RECHERCHE, compendiumIds);
    await this.$prepareCompendiums();
  }

  async $prepareCompendiums() {
    this.compendiums = game.settings.get(SYSTEM_RDD, COMPENDIUMS_RECHERCHE).filter(c => SystemCompendiums.getPack(c));

    this.compendiumTables = this.compendiums.map(it => new CompendiumTable(it, 'Item'));
    const compendiumItems = await this.getElements(it => 1, it => it.isInventaire());
    const fromCompendiums = Misc.concat(compendiumItems.map(it => it.getMilieux().filter(m => m)));
    this.mapMilieux = Misc.indexLowercase(fromCompendiums);
  }

  async autresMilieux(item) {
    const milieuxExistants = item.getMilieux().map(it => Grammar.toLowerCaseNoAccent(it));
    return Object.keys(this.mapMilieux)
      .filter(it => !milieuxExistants.includes(it))
      .map(it => this.mapMilieux[it]);
  }

  async getElements(itemFrequence, filter) {
    const compendiumsElement = await Promise.all(
      this.compendiumTables.map(async compTable => await compTable.getContent(itemFrequence, filter))
    );
    const elements = compendiumsElement.reduce((a, b) => a.concat(b));
    elements.sort(Misc.ascending(it => it.name))
    return elements;
  }

  async buildTable(itemFrequence, filter = it => true) {
    if (!itemFrequence) {
      itemFrequence = it => it.getFrequence()
    }
    const elements = await this.getElements(itemFrequence, filter);;
    return CompendiumTableHelpers.buildTable(elements, itemFrequence);
  }
}
