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

const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api

export const EXPORT_CSV_SCRIPTARIUM = 'export-csv-scriptarium'
export const ROLL_DIALOG_V2 = 'roll-dialog-v2'

const OPTIONS_AVANCEES = [
  { group: 'Fenêtres', name: ROLL_DIALOG_V2, descr: "Utiliser les nouvelles fenêtres de jet", default: false },
  { group: 'Menus', name: EXPORT_CSV_SCRIPTARIUM, descr: "Proposer le menu d'export csv Scriptarium", default: false },
]

export class OptionsAvancees extends HandlebarsApplicationMixin(ApplicationV2) {
  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
    })
  }

  static DEFAULT_OPTIONS = {
    tag: "form",
    id: "options-avancees",
    classes: ["options-avancees"],
    form: { submitOnChange: false, closeOnSubmit: true },
    position: { width: 550, height: 650 },
    window: { title: "Options avancées", icon: "fa-solid fa-bars" }
  }

  static PARTS = {
    form: { template: "systems/foundryvtt-reve-de-dragon/templates/settings/options-avancees.hbs" }
  }

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

  async _prepareContext() {
    const regles = OPTIONS_AVANCEES.filter(it => game.user.isGM || it.scope == "client")
      .map(it => {
        it = foundry.utils.deepClone(it)
        it.id = OptionsAvancees._getId(it.name)
        it.active = OptionsAvancees.isUsing(it.name)
        return it
      })
    return {
      regles,
      groups: Misc.classify(regles, it => it.group),
    }
  }

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

  static isUsing(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)
  }

  async _onRender(context, options) {
    this.element.querySelectorAll(".select-option").forEach(el => {
      el.addEventListener("click", async event => {
        const id = event.currentTarget.getAttribute("name")
        if (id) {
          const isChecked = event.currentTarget.checked
          await game.settings.set(SYSTEM_RDD, id, isChecked)
        }
      })
    })
  }
}
