import { SYSTEM_RDD } from "../constants.js"
import { Misc } from "../misc.js"

export const EXPORT_CSV_SCRIPTARIUM = 'export-csv-scriptarium'

const OPTIONS_AVANCEES = [
  { group: 'Menus', name: EXPORT_CSV_SCRIPTARIUM, descr: "Proposer le menu d'export csv Scriptarium" },
]

export class OptionsAvancees extends FormApplication {
  static initSettings() {
    for (const regle of OPTIONS_AVANCEES) {
      const name = regle.name
      const id = OptionsAvancees._getId(name)
      game.settings.register(SYSTEM_RDD, id, { name: id, scope: regle.scope ?? "world", config: false, default: regle.default == undefined ? true : regle.default, type: Boolean })
    }

    game.settings.registerMenu(SYSTEM_RDD, "rdd-options-avancees", {
      name: "Configurer les options avancées",
      label: "Options avancées",
      hint: "Ouvre la fenêtre de configuration des options avancées",
      icon: "fas fa-bars",
      type: OptionsAvancees
    })
  }

  constructor(...args) {
    super(...args)
  }

  static _getId(name) {
    return `rdd-advanced-${name}`
  }

  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      id: "options-avancees",
      template: "systems/foundryvtt-reve-de-dragon/templates/settings/options-avancees.hbs",
      height: 650,
      width: 550,
      minimizable: false,
      closeOnSubmit: true,
      title: "Options avancées"
    }, { inplace: false })
  }

  getData() {
    let formData = super.getData()
    const regles = OPTIONS_AVANCEES.filter(it => game.user.isGM || it.scope == "client")
      .map(it => {
        it = foundry.utils.duplicate(it)
        it.id = OptionsAvancees._getId(it.name)
        it.active = OptionsAvancees.isSet(it.name)
        return it
      })
    formData.regles = regles
    formData.groups = Misc.classify(regles, it => it.group)
    return formData
  }

  static getSettingKey(name){
    return `${SYSTEM_RDD}.${this._getId(name)}`
  }

  static isUsing(name) {
    return OptionsAvancees.isSet(name)
  }

  static isSet(name) {
    return game.settings.get(SYSTEM_RDD, OptionsAvancees._getId(name))
  }

  static set(name, value) {
    return game.settings.set(SYSTEM_RDD, OptionsAvancees._getId(name), value ? true : false)
  }

  activateListeners(html) {
    html.find(".select-option").click((event) => {
      if (event.currentTarget.attributes.name) {
        let id = event.currentTarget.attributes.name.value
        let isChecked = event.currentTarget.checked
        game.settings.set(SYSTEM_RDD, id, isChecked)
      }
    })
  }

  async _updateObject(event, formData) {
    this.close()
  }
}

