import { RFRPUtility } from "../../rfrp-utility.js";

export default class RMSSToolsSCImporter extends FormApplication {

  constructor(selectOptions, character) {
    super();
    this.selectOptions = selectOptions;
    this.character = character;
  }

  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      classes: ["form"],
      popOut: true,
      title: "Import Skill Categories",
      template: "systems/fvtt-rolemaster-frp/templates/sheets/apps/app_skill_category_importer.html"
    });
  }

  getData() {
    // Send data to the template
    return {
      selectOptions: this.selectOptions
    };
  }

  activateListeners(html) {
    super.activateListeners(html);
  }

  async _updateObject(event, formData) {
    //console.log("Update ", event, formData);
    let itemType = event.submitter.value;
    let toDelete = [];
    for (const item of this.character.items) {
      if (item.type === itemType) {
        toDelete.push(item.id);
      }
    }
    this.character.deleteEmbeddedDocuments("Item", toDelete);

    let comp = (itemType == "skill") ? formData.selectOptionsSkills : formData.selectOptionsCategories;
    const pack = game.packs.get(comp);
    const skillCategoryData = await pack.getIndex();

    console.log("Importing New Skills/Skill Categories.");
    let gameSystem = RFRPUtility.getGameSystem();
    for (const sc of skillCategoryData) {
      const newitem = await pack.getDocument(sc._id);
      
      let newDocuments = [];
      if (newitem.type === itemType && (newitem.system.game_system === "common" || newitem.system.game_system === gameSystem)) {
        //console.log(newitem);
        newDocuments.push(newitem);
      }
      if (newDocuments.length > 0) {
        await Item.createDocuments(newDocuments, {parent: this.character});
      }
    }
  }
}

