import { renderTemplate } from "../constants.js"
import { Misc } from "../misc.js"
import { RdDUtility } from "../rdd-utility.js"
import { ChatVente } from "./chat-vente.js"

export class DialogItemAchat extends foundry.applications.api.DialogV2 {
  static preparerAchat(chatButton) {
    return ChatVente.getDetailAchatVente(RdDUtility.findChatMessageId(chatButton))
  }

  static async onAcheter({ item, vendeur, acheteur, tailleLot, prixLot, nbLots, quantiteIllimite, chatMessageIdVente }) {
    const venteData = {
      item,
      actingUserId: game.user.id,
      vendeur,
      acheteur,
      tailleLot,
      quantiteIllimite,
      nbLots,
      choix: { seForcer: false, supprimerSiZero: true },
      prixLot,
      isVente: prixLot > 0,
      isConsommable: item.type == "nourritureboisson" && acheteur?.isPersonnage(),
      chatMessageIdVente
    }
    if (venteData.vendeur?.id == venteData.acheteur?.id) {
      ui.notifications.info("Inutile de se vendre à soi-même")
      return
    }
    DialogItemAchat.changeNombreLots(venteData, 1)
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-item-achat.hbs", venteData)
    new DialogItemAchat(content, venteData).render({ force: true })
  }

  static changeNombreLots(venteData, nombreLots) {
    venteData.choix.nombreLots = nombreLots
    venteData.prixTotal = (nombreLots * venteData.prixLot).toFixed(2)
    if (venteData.isConsommable) {
      const doses = nombreLots * venteData.tailleLot
      venteData.totalSust = Misc.keepDecimals(doses * (venteData.item.system.sust ?? 0), 2)
      venteData.totalDesaltere = venteData.item.system.boisson
        ? Misc.keepDecimals(doses * (venteData.item.system.desaltere ?? 0), 2)
        : 0
    }
  }

  constructor(content, venteData) {
    const actionAchat = venteData.prixLot > 0 ? "Acheter" : "Prendre"
    const buttons = []
    if (venteData.isConsommable) {
      buttons.push({
        label: venteData.item.system.boisson ? "Boire" : "Manger",
        action: "consommer",
        callback: () => this.onAchatConsommer()
      })
    }
    buttons.push({ label: actionAchat, action: actionAchat, callback: () => this.onAchat() })
    buttons.push({ label: "Décliner", action: "decliner", callback: () => {} })
    const acheteur = venteData.acheteur?.name ?? "Un acheteur"
    const vendeur = venteData.vendeur?.name ?? "Un vendeur"
    super({
      title: `${acheteur} - ${actionAchat} à ${vendeur}`,
      content,
      classes: ["dialogachat"],
      position: { width: 400, height: 'fit-content' },
      buttons
    })
    this.venteData = venteData
  }

  _onRender(context) {
    super._onRender(context)
    this.element.querySelector(".nombreLots")?.addEventListener("change", event => this.setNombreLots(Number(event.currentTarget.value)))
    this.element.querySelector(".se-forcer")?.addEventListener("change", event => this.setSeForcer(event))
  }

  async onAchat() {
    const el = this.element
    el.querySelector(".nombreLots")?.dispatchEvent(new Event("change"))
    ;(this.venteData.vendeur ?? this.venteData.acheteur).achatVente({
      userId: game.user.id,
      vendeurId: this.venteData.vendeur?.id,
      acheteurId: this.venteData.acheteur?.id,
      prixTotal: this.venteData.prixTotal,
      chatMessageIdVente: this.venteData.chatMessageIdVente,
      choix: this.venteData.choix,
      vente: this.venteData
    })
  }

  async onAchatConsommer() {
    this.venteData.choix.consommer = true
    await this.onAchat()
  }

  setSeForcer(event) {
    this.venteData.choix.seForcer = event.currentTarget.checked
  }

  setNombreLots(nbLots) {
    if (!this.venteData.quantiteIllimite) {
      if (nbLots > this.venteData.nbLots) {
        ui.notifications.warn(`Seulement ${this.venteData.nbLots} lots disponibles, vous ne pouvez pas en prendre ${nbLots}`)
      }
      nbLots = Math.min(nbLots, this.venteData.nbLots)
    }
    DialogItemAchat.changeNombreLots(this.venteData, nbLots)
    const el = this.element
    const nbl = el.querySelector(".nombreLots")
    if (nbl) nbl.value = nbLots
    const pt = el.querySelector(".prixTotal")
    if (pt) pt.textContent = this.venteData.prixTotal
    const sust = el.querySelector("span.total-sust")
    if (sust) sust.textContent = this.venteData.totalSust
    const des = el.querySelector("span.total-desaltere")
    if (des) des.textContent = this.venteData.totalDesaltere
  }
}
