import { MaleficesUtility } from "./malefices-utility.js";

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

export class MaleficesTirageTarotDialog extends HandlebarsApplicationMixin(ApplicationV2) {

  /* -------------------------------------------- */
  static DEFAULT_OPTIONS = {
    id: "malefices-tirage-tarot",
    classes: ["MaleficesDialog"],
    window: { title: "Tirage des Tarots", resizable: true },
    position: { width: 720, height: 740 },
  }

  static PARTS = {
    form: { template: 'systems/fvtt-malefices/templates/dialogs/tirage-tarot-dialog.hbs' }
  }

  /* -------------------------------------------- */
  constructor(actor, tirageData, options = {}) {
    super(options)
    this.actor = actor
    this.tirageData = tirageData
  }

  /* -------------------------------------------- */
  static async create(actor, tirageData) {
    const app = new MaleficesTirageTarotDialog(actor, tirageData)
    app.render({ force: true })
    return app
  }

  /* -------------------------------------------- */
  async _prepareContext(_options) {
    return { ...this.tirageData }
  }

  /* -------------------------------------------- */
  _onRender(_context, _options) {
    const el = this.element

    el.querySelector('#playerId')?.addEventListener('change', (event) => {
      if (event.currentTarget.value !== "none") {
        this.tirageData.playerId = event.currentTarget.value
        this.processSelectedPlayer()
      }
    })

    el.querySelector('#actorId')?.addEventListener('change', (event) => {
      if (event.currentTarget.value !== "none") {
        this.attributeToActor(event.currentTarget.value)
      }
    })

    el.querySelector('.tirage-close-btn')?.addEventListener('click', () => this.close())
  }

  /* -------------------------------------------- */
  async sendCardRequest() {
    this.tirageData.state = 'waiting-user-card'
    await MaleficesUtility.createChatMessage(this.tirageData.user.name, "useronly", {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-malefices/templates/chat/request-tarot-card.hbs`, this.tirageData)
    })
  }

  /* -------------------------------------------- */
  drawCard() {
    let index = Math.round(Math.random() * (this.tirageData.deck.length - 1))
    let selectedCard = this.tirageData.deck[index]
    selectedCard.system.ispositif = true
    if (selectedCard.system.isdualside) {
      selectedCard.system.ispositif = (Math.random() > 0.5)
    }
    // Cas spécial de la Roue de la Fortune
    if (selectedCard.name.toLowerCase().includes("fortune")) {
      this.tirageData.maxPlayerCard += 1
      this.tirageData.maxSecretCard += 1
    }
    this.tirageData.deck = this.tirageData.deck.filter(c => c.name !== selectedCard.name)
    return selectedCard
  }

  /* -------------------------------------------- */
  async addCard(msgId) {
    MaleficesUtility.removeChatMessageId(msgId)

    let selectedCard = this.drawCard()
    selectedCard.system.isgm = false
    await MaleficesUtility.createChatMessage(this.tirageData.user.name, "gmroll", {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-malefices/templates/chat/display-tarot-card.hbs`, selectedCard)
    })
    if (this.tirageData.cards[0].name == "???") this.tirageData.cards.shift()
    this.tirageData.cards.push(selectedCard)
    this.tirageData.nbCard++

    if (this.tirageData.nbCard == this.tirageData.maxPlayerCard) {
      for (let i = 0; i < this.tirageData.maxSecretCard; i++) {
        let secretCard = this.drawCard()
        secretCard.system.isgm = true
        await MaleficesUtility.createChatMessage(this.tirageData.user.name, "blindroll", {
          content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-malefices/templates/chat/display-tarot-card.hbs`, secretCard)
        })
        if (this.tirageData.secretCards[0].name == "???") this.tirageData.secretCards.shift()
        this.tirageData.secretCards.push(secretCard)
      }
      this.tirageData.actors = foundry.utils.duplicate(game.actors)
      this.tirageData.state = 'attribute-to-actor'
    } else {
      this.sendCardRequest()
    }
    this.render({ force: true })
  }

  /* -------------------------------------------- */
  async processSelectedPlayer() {
    this.tirageData.user = game.users.get(this.tirageData.playerId)
    this.tirageData.players = null
    game.system.malefices.currentTirage = this
    this.render({ force: true })
    this.sendCardRequest()
  }

  /* -------------------------------------------- */
  attributeToActor(actorId) {
    const actor = game.actors.get(actorId)
    if (actor) {
      actor.createEmbeddedDocuments('Item', this.tirageData.cards)
      actor.createEmbeddedDocuments('Item', this.tirageData.secretCards)
      ui.notifications.info("Les cartes ont été attribuées à " + actor.name)
    }
  }
}