import OathHammerActorSheet from "./base-actor-sheet.mjs"
import { rollInitiativeCheck } from "../../rolls.mjs"

export default class OathHammerNPCSheet extends OathHammerActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["npc"],
    position: {
      width: 720,
      height: "auto",
    },
    window: {
      contentClasses: ["npc-content"],
    },
    actions: {
      rollInitiative: OathHammerNPCSheet.#onRollInitiative,
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-oath-hammer/templates/actor/npc-sheet.hbs",
    },
    tabs: {
      template: "templates/generic/tab-navigation.hbs",
    },
    combat: {
      template: "systems/fvtt-oath-hammer/templates/actor/npc-combat.hbs",
    },
    notes: {
      template: "systems/fvtt-oath-hammer/templates/actor/npc-notes.hbs",
    },
  }

  /** @override */
  tabGroups = {
    sheet: "combat",
  }

  #getTabs() {
    const tabs = {
      combat: { id: "combat", group: "sheet", icon: "fa-solid fa-swords", label: "OATHHAMMER.Tab.Combat" },
      notes: { id: "notes", group: "sheet", icon: "fa-solid fa-book", label: "OATHHAMMER.Tab.Notes" },
    }
    for (const v of Object.values(tabs)) {
      v.active = this.tabGroups[v.group] === v.id
      v.cssClass = v.active ? "active" : ""
    }
    return tabs
  }

  /** @override */
  async _prepareContext() {
    const context = await super._prepareContext()
    context.tabs = this.#getTabs()
    return context
  }

  /** @override */
  async _preparePartContext(partId, context) {
    const doc = this.document
    switch (partId) {
      case "main":
        break
      case "combat":
        context.tab = context.tabs.combat
        context.weapons = doc.itemTypes.weapon
        context.combatantInitiative = game.combat?.combatants.find(c => c.actor?.id === doc.id)?.initiative ?? null
        break
      case "notes":
        context.tab = context.tabs.notes
        context.enrichedDescription = await foundry.applications.ux.TextEditor.implementation.enrichHTML(doc.system.description, { async: true })
        context.enrichedNotes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(doc.system.notes, { async: true })
        break
    }
    return context
  }

  async _onDrop(event) {
    if (!this.isEditable || !this.isEditMode) return
    const data = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)
    if (data.type === "Item") {
      const item = await fromUuid(data.uuid)
      return this._onDropItem(item)
    }
  }

  static async #onRollInitiative() {
    const actor = this.document
    const combatant = game.combat?.combatants.find(c => c.actor?.id === actor.id)
    if (combatant) {
      await game.combat.rollInitiative([combatant.id])
    } else {
      await rollInitiativeCheck(actor)
    }
  }
}
