import { ChatUtility } from "../chat-utility.js"
import { Misc } from "../misc.js"
import { RdDTimestamp } from "../time/rdd-timestamp.js"

const fields = foundry.applications.fields

export class DialogFlushByDate {

  static async init() {
    Hooks.once("renderChatLog", async () => await DialogFlushByDate.onFirstRenderChatLog())
  }

  static async onFirstRenderChatLog() {
    if (game.user.isGM) {
      const content = await foundry.applications.handlebars.renderTemplate('systems/foundryvtt-reve-de-dragon/templates/chat/button-flush-by-date.hbs')
      const flushButton = document.querySelector("#chat-controls button[data-action='flush']")
      if (!flushButton) return
      flushButton.insertAdjacentHTML("afterend", content)
      flushButton.parentElement.querySelector("button[name='flush-by-date']")?.addEventListener(
        "click", e => {
          if (game.messages.size > 0) {
            DialogFlushByDate.create()
          }
          else {
            ui.notifications.info("Aucun message à supprimer!")
          }
          e.preventDefault()
        })
    }
  }

  static async create() {
    const dates = DialogFlushByDate.getChatMessageDates(game.messages)

    const selectGroup = fields.createFormGroup({
      input: fields.createSelectInput({
        options: dates.map(it => { return { label: `${it.dateTerre} | ${it.dateReve}`, value: it.timestamp } }),
        name: 'timestamp'
      }),
      label: 'Messages antérieurs au',
      hint: 'Supprimer les messages antérieurs à la date'
    })

    const selected = await foundry.applications.api.DialogV2.input({
      window: { title: "Supprimer les messages du tchat" },
      content: selectGroup.outerHTML,
      ok: {
        label: "Supprimer",
        icon: "fa-solid fa-trash-can",
      }
    })
    if (selected) {
      const timestamp = Number.parseInt(selected.timestamp)
      const toDelete = game.messages.filter(it => it.timestamp < timestamp)
      toDelete.forEach(it => it.delete())
    }
  }

  static getChatMessageDates(messages) {
    const datesTerre = Object.values(Misc.classifyFirst(messages,
      m => ChatUtility.getISODate(m),
      m => DialogFlushByDate.chatMessageDates(m)))
    const timestamps = new Set(datesTerre.map(it => it.timestamp))
    const datesReve = Object.values(Misc.classifyFirst(messages,
      m => RdDTimestamp.fromChatMessage(m)?.isoDate() ?? "date inconnue",
      m => DialogFlushByDate.chatMessageDates(m)))
    const dates = [...datesTerre, ...datesReve.filter(it => !timestamps.has(it.timestamp))]
    return dates.sort(Misc.ascending(it => it.timestamp))
  }

  static chatMessageDates(it) {
    return {
      timestamp: it.timestamp,
      dateTerre: new Date(it.timestamp).toLocaleDateString(),
      dateReve: RdDTimestamp.fromChatMessage(it)?.formatDate() ?? "—"
    }
  }
}