const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api
import { SYSTEM } from "../config/system.mjs"

/**
 * An application for configuring the permissions which are available to each User role.
 * @extends ApplicationV2
 * @mixes HandlebarsApplication
 * @alias PermissionConfig
 */
export default class LethalFantasyManager extends HandlebarsApplicationMixin(ApplicationV2) {
  static DEFAULT_OPTIONS = {
    id: "lethalfantasy-application-manager",
    tag: "form",
    window: {
      contentClasses: ["lethalfantasy-manager"],
      title: "LETHALFANTASY.Manager.title",
      resizable: true,
    },
    position: {
      width: "auto",
      height: "auto",
      top: 80,
      left: 400,
    },
    form: {
      closeOnSubmit: true,
    },
    actions: {
      resourceAll: LethalFantasyManager.#onResourceAll,
      resourceOne: LethalFantasyManager.#onResourceOne,
      saveAll: LethalFantasyManager.#onSaveAll,
      saveOne: LethalFantasyManager.#onSaveOne,
      openSheet: LethalFantasyManager.#onOpenSheet,
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-lethal-fantasy/templates/manager.hbs",
    },
  }

  /* -------------------------------------------- */
  /*  Rendering                                   */
  /* -------------------------------------------- */

  /** @override */
  async _prepareContext(_options = {}) {
    return {
      players: game.users.filter((u) => u.hasPlayerOwner && u.active),
    }
  }

  static async #onResourceAll(event, target) {
    const value = event.target.dataset.resource
    LethalFantasyManager.askRollForAll("resource", value)
  }

  static async #onSaveAll(event, target) {
    const value = event.target.dataset.save
    LethalFantasyManager.askRollForAll("save", value)
  }

  static #onResourceOne(event, target) {
    const value = event.target.dataset.resource
    const recipient = event.target.parentElement.dataset.userId
    const name = event.target.parentElement.dataset.characterName
    LethalFantasyManager.askRollForOne("resource", value, recipient, name)
  }

  static async #onSaveOne(event, target) {
    const value = event.target.dataset.save
    const recipient = event.target.parentElement.dataset.userId
    const name = event.target.parentElement.dataset.characterName
    LethalFantasyManager.askRollForOne("save", value, recipient, name)
  }

  static #onOpenSheet(event, target) {
    const characterId = event.target.dataset.characterId
    game.actors.get(characterId).sheet.render(true)
  }

  static async askRollForAll(type, value, title = null, avantage = null) {
    let label = game.i18n.localize(`LETHALFANTASY.Manager.${value}`)
    let text = game.i18n.format("LETHALFANTASY.Chat.askRollForAll", { value: label })

    if (avantage) {
      switch (avantage) {
        case "++":
          text += ` ${game.i18n.localize("LETHALFANTASY.Roll.doubleAvantage")}`
          break
        case "+":
          text += ` ${game.i18n.localize("LETHALFANTASY.Roll.avantage")}`
          break
        case "-":
          text += ` ${game.i18n.localize("LETHALFANTASY.Roll.desavantage")}`
          break
        case "--":
          text += ` ${game.i18n.localize("LETHALFANTASY.Roll.doubleDesavantage")}`
          break
        default:
          break
      }
    }

    ChatMessage.create({
      user: game.user.id,
      content: await renderTemplate(`systems/fvtt-lethal-fantasy/templates/chat-ask-roll.hbs`, {
        title: title !== null ? title : "",
        text: text,
        rollType: type,
        value: value,
        avantage: avantage,
      }),
      flags: { tenebris: { typeMessage: "askRoll" } },
    })
  }

  static async askRollForOne(type, value, recipient, name) {
    let label = game.i18n.localize(`LETHALFANTASY.Manager.${value}`)
    const text = game.i18n.format("LETHALFANTASY.Chat.askRollForOne", { value: label, name: name })

    game.socket.emit(`system.${SYSTEM.id}`, {
      action: "askRoll",
      data: {
        userId: recipient,
      },
    })

    ChatMessage.create({
      user: game.user.id,
      content: await renderTemplate(`systems/fvtt-lethal-fantasy/templates/chat-ask-roll.hbs`, {
        text: text,
        rollType: type,
        value: value,
      }),
      whisper: [recipient],
      flags: { tenebris: { typeMessage: "askRoll" } },
    })
  }
}
