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

export class MaleficesTirageTarotDialog extends Dialog {

  /* -------------------------------------------- */
  static async create(actor, tirageData) {

    let options = { classes: ["MaleficesDialog"], width: 720, height: 740, 'z-index': 99999 };
    let html = await foundry.applications.handlebars.renderTemplate('systems/fvtt-malefices/templates/dialogs/tirage-tarot-dialog.hbs', tirageData);

    return new MaleficesTirageTarotDialog(actor, tirageData, html, options);
  }

  /* -------------------------------------------- */
  constructor(actor, tirageData, html, options, close = undefined) {
    let conf = {
      title: "Tirage des tarots",
      content: html,
      buttons: {
        cancel: {
          icon: '<i class="fas fa-times"></i>',
          label: "Fermer/Annuler",
          callback: () => { this.close() }
        }
      },
      close: close
    }

    super(conf, options);

    this.actor = actor;
    this.tirageData = tirageData;
  }

  /* -------------------------------------------- */
  async sendCardRequest() {
    this.tirageData.state = 'waiting-user-card'
    let msg = await MaleficesUtility.createChatMessage(this.tirageData.user.name, "useronly", {
      content: await renderTemplate(`systems/fvtt-malefices/templates/chat/request-tarot-card.hbs`, this.tirageData)
    })
    //msg.setFlag("world", "tirage-data", this.tirageData)
    console.log("MSG IS", msg)
  }

  /* -------------------------------------------- */
  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) { // Cas des cartes pouvant avoir 2 sens
      selectedCard.system.ispositif = (Math.random() > 0.5)
    }
    console.log("CARD SELECTED:", selectedCard)
    // Cas spécial de la Roue de la Fortune
    if ( selectedCard.name.toLowerCase().includes("fortune")) {
      this.tirageData.maxPlayerCard += 1
      this.tirageData.maxSecretCard += 1
    }
    let newList = []
    for(let card of this.tirageData.deck) {
      if (card.name != selectedCard.name) {
        newList.push(card)
      }
    }
    this.tirageData.deck = newList

    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 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 selectedCard = this.drawCard()
        selectedCard.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`, selectedCard)
        })
        if (this.tirageData.secretCards[0].name == "???") {
          this.tirageData.secretCards.shift()
        }
        this.tirageData.secretCards.push(selectedCard)
      }
      this.tirageData.actors = foundry.utils.duplicate(game.actors)
      this.tirageData.state = 'attribute-to-actor'
    }else {
      this.sendCardRequest()
    }
    this.refreshDialog()
  }

  /* -------------------------------------------- */
  async processSelectedPlayer() {
    let user = game.users.get(this.tirageData.playerId)
    this.tirageData.user  = user
    this.tirageData.players = null
    console.log("Going to work with ", user.name)
    game.system.malefices.currentTirage = this
    this.refreshDialog()
    this.sendCardRequest()
  }

  /* -------------------------------------------- */
  attributeToActor(actorId) {
    let 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)
    }
  }
  /* -------------------------------------------- */
  async refreshDialog() {
    const content = await foundry.applications.handlebars.renderTemplate("systems/fvtt-malefices/templates/dialogs/tirage-tarot-dialog.hbs", this.tirageData)
    this.data.content = content
    this.render(true)
  }

  /* -------------------------------------------- */
  activateListeners(html) {
    super.activateListeners(html);

    let dialog = this;
    function onLoad() {
    }
    $(function () { onLoad(); });

    html.find('#playerId').change((event) => {
      if ( event.currentTarget.value != "none") {
        dialog.tirageData.playerId = event.currentTarget.value
        dialog.processSelectedPlayer()
      }
    })
    html.find('#actorId').change((event) => {
      if ( event.currentTarget.value != "none") {
        let actorId = event.currentTarget.value
        dialog.attributeToActor(actorId)
      }
    })

  }
}