import { ACTOR_TYPES } from "../../constants.js"
import { Misc } from "../../misc.js"
import { EXPORT_CSV_SCRIPTARIUM, OptionsAvancees } from "../../settings/options-avancees.js"
import { Mapping } from "./mapping.js"

const IMG_SCRIPTARIUM = '<img class="context-menu-img" src="systems/foundryvtt-reve-de-dragon/assets/ui/scriptarium.svg">'

export class ExportScriptarium {

  static init() {
    ExportScriptarium.INSTANCE = new ExportScriptarium()
  }

  constructor() {
    //Hooks.on("getActorDirectoryFolderContext", (actorDirectory, menus) => { ExportScriptarium.INSTANCE.onActorDirectoryMenu(actorDirectory, menus) })
    Hooks.on("getFolderContextOptions", (actorDirectory, menus) => { ExportScriptarium.INSTANCE.onActorDirectoryMenu(actorDirectory, menus) })
    //Hooks.on("getActorDirectoryEntryContext", (actorDirectory, menus) => { ExportScriptarium.INSTANCE.onActorDirectoryMenu(actorDirectory, menus) })
    Hooks.on("getActorContextOptions", (actorDirectory, menus) => { ExportScriptarium.INSTANCE.onActorDirectoryMenu(actorDirectory, menus) })

  }

  onActorDirectoryMenu(actorDirectory, menus) {
    // DEBUG console.log("ExportScriptarium.onActorDirectoryMenu", actorDirectory, menus)
    menus.push({
      name: 'Export Personnages',
      icon: '<i class="fa-solid fa-download"></i>', //IMG_SCRIPTARIUM,
      condition: (target) => game.user.isGM &&
        OptionsAvancees.isUsing(EXPORT_CSV_SCRIPTARIUM) &&
        this.$getActors(actorDirectory, target).length > 0,
      callback: target => this.exportActors(this.$getActors(actorDirectory, target), this.$getTargetName(actorDirectory, target))
    })
  }

  $getTargetName(actorDirectory, target) {
    target = $(target)
    const li = target.closest(".directory-item")
    const folderId = li.data("folderId")
    const actorId = li.data("entryId")
    return actorId
      ? game.actors.get(actorId).name
      : actorDirectory.collection.filter(it => it.folder.id == folderId).name
  }

  $getActors(actorDirectory, target) {
    if (actorDirectory.id != "actors") {
      return []
    }
    // DEBUG console.log("ExportScriptarium.$getActors", actorDirectory, target)
    target = $(target)
    const li = target.closest(".directory-item")
    const folderId = li.data("folderId")
    const actorId = li.data("entryId")
    const actors = actorId
      ? [game.actors.get(actorId)]
      : folderId
        ? actorDirectory.collection.filter(it => it.folder.id == folderId)
        : []
    return actors.filter(it => it.type == ACTOR_TYPES.personnage)
  }

  exportActors(actors, targetName) {
    const eol = '\n\r'
    const header = Misc.join(this.getHeaderLine(), ';')
    const actorLines = actors.map(actor => Misc.join(this.getActorLine(actor), ';'))
    const data = Misc.join([header, ...actorLines], eol)
    const filename = `scriptarium-${targetName?.slugify()}.csv`;
    foundry.utils.saveDataToFile(data, "text/csv;charset=windows-1252", `${filename}`);
  }

  getHeaderLine() {
    return Mapping.getColumns()
  }

  getActorLine(actor) {
    const values = Mapping.getValues(actor)
    return values
      .map(it => this.$escapeQuotes(it))
      .map(it => it.replaceAll("\n", " ").replaceAll("\r", ""))
  }

  $escapeQuotes(it) {
    it = '' + it
    if (it.includes('"') || it.includes(';')) {
      return `"${it.replaceAll('"', '\\"')}"`
    }
    return it
  }
}
