// System Module Imports
import { Utils } from './utils.js'
import { SYSTEM } from "../../config/system.mjs"
export let ActionHandler = null

Hooks.once('tokenActionHudCoreApiReady', async (coreModule) => {
  /**
   * Extends Token Action HUD Core's ActionHandler class and builds system-defined actions for the HUD
   */
  ActionHandler = class ActionHandler extends coreModule.api.ActionHandler {
    /**
     * Build system actions
     * Called by Token Action HUD Core
     * @override
     * @param {array} groupIds
     */
    async buildSystemActions(groupIds) {
      // Set actor and token variables
      this.actors = (!this.actor) ? this._getActors() : [this.actor]
      this.actorType = this.actor?.type

      // Set items variable
      if (this.actor) {
        let items = this.actor.items
        items = coreModule.api.Utils.sortItemsByName(items)
        this.items = items
      }

      if (this.actorType !== 'vehicle') {
        this.#buildCharacterActions()
      } else if (!this.actor) {
        this.#buildMultipleTokenActions()
      }
    }

    /**
     * Build character actions
     * @private
     */
    #buildCharacterActions() {
      this.buildAttributes()
      this.buildOther()
      this.buildLuck()
      this.buildSkills()
      this.buildEquipment()
    }

    #showValue() {
      return game.settings.get('token-action-hud-core', 'tooltips') === 'none'
    }

    async buildAttributes() {
      const actions = []
      for (const key in this.actor.system.characteristics) {
        const encodedValue = [coreModule.api.Utils.i18n('attributes'), key].join(this.delimiter)
        const tooltip = {
          content: String(this.actor.system.characteristics[key].value * 5),
          class: 'tah-system-tooltip',
          direction: 'LEFT'
        }
        actions.push({
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.' + key),
          id: key,
          info1: this.#showValue() ? { text: tooltip.content } : null,
          tooltip,
          encodedValue
        })
      }
      await this.addActions(actions, {
        id: 'attributes',
        type: 'system'
      })
    }

    async buildLuck() {
      const actions = []
      const tooltip = {
        content: '50',
        class: 'tah-system-tooltip',
        direction: 'LEFT'
      }
      actions.push({
        name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.Luck'),
        id: 'luck',
        info1: this.#showValue() ? { text: '50' } : null,
        tooltip,
        encodedValue: ['attributes', 'luck'].join(this.delimiter)
      })
      await this.addActions(actions, { id: 'luck', type: 'system' })
    }

    async buildOther() {
      if (typeof this.actor.system.sanity.value !== 'undefined') {
        const actions = []
        const groupData = {
          id: 'other_sanity',
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.SAN'),
          type: 'system'
        }
        this.addGroup(groupData, { id: 'other', type: 'system' }, true)
        const tooltip = {
          content: String(this.actor.system.san.value + '/' + this.actor.system.san.max),
          class: 'tah-system-tooltip',
          direction: 'LEFT'
        }
        actions.push({
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.SAN'),
          id: 'sanity',
          info1: this.#showValue() ? { text: tooltip.content } : null,
          tooltip,
          encodedValue: ['attributes', 'sanity'].join(this.delimiter)
        },
          {
            name: '+',
            id: 'sanity_add',
            encodedValue: ['attributes', 'sanity_add'].join(this.delimiter)
          },
          {
            name: '-',
            id: 'sanity_subtract',
            encodedValue: ['attributes', 'sanity_subtract'].join(this.delimiter)
          })
        await this.addActions(actions, { id: 'other_sanity', type: 'system' })
      }
      if (typeof this.actor.system.hp.value !== 'undefined') {
        const actions = []
        const groupData = {
          id: 'other_health',
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.HP'),
          type: 'system'
        }
        this.addGroup(groupData, { id: 'other', type: 'system' }, true)
        const tooltip = {
          content: String(this.actor.system.hp.value + '/' + this.actor.system.hp.max),
          class: 'tah-system-tooltip',
          direction: 'LEFT'
        }
        actions.push({
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.HP'),
          id: 'health',
          info1: this.#showValue() ? { text: tooltip.content } : null,
          tooltip,
          encodedValue: ['attributes', 'health'].join(this.delimiter)
        },
          {
            name: '+',
            id: 'health_add',
            encodedValue: ['attributes', 'health_add'].join(this.delimiter)
          },
          {
            name: '-',
            id: 'health_subtract',
            encodedValue: ['attributes', 'health_subtract'].join(this.delimiter)
          })
        await this.addActions(actions, { id: 'other_health', type: 'system' })
      }
      if (typeof this.actor.system.wp.value !== 'undefined') {
        const actions = []
        const groupData = {
          id: 'other_wp',
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.WP'),
          type: 'system'
        }
        this.addGroup(groupData, { id: 'other', type: 'system' }, true)
        const tooltip = {
          content: String(this.actor.system.wp.value + '/' + this.actor.system.wp.max),
          class: 'tah-system-tooltip',
          direction: 'LEFT'
        }
        actions.push({
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.WP'),
          id: 'wp',
          info1: this.#showValue() ? { text: tooltip.content } : null,
          tooltip,
          encodedValue: ['attributes', 'wp'].join(this.delimiter)
        },
          {
            name: '+',
            id: 'wp_add',
            encodedValue: ['attributes', 'wp_add'].join(this.delimiter)
          },
          {
            name: '-',
            id: 'wp_subtract',
            encodedValue: ['attributes', 'wp_subtract'].join(this.delimiter)
          })
        await this.addActions(actions, { id: 'other_wp', type: 'system' })
      }
    }

    async buildSkills() {
      const actions = []
      let actorSkills = this.actor.items.filter(item => item.type === 'skill')
      for (const skill in actorSkills) {
        if (skill.system.computeScore() > 0) {
          const tooltip = {
            content: String(skill.skill.system.computeScore()),
            direction: 'LEFT'
          }
          actions.push({
            name: skill.name,
            id: skill.id,
            info1: this.#showValue() ? { text: tooltip.content } : null,
            tooltip,
            encodedValue: ['skills', s].join(this.delimiter)
          })
        }
      }
      await this.addActions(actions, { id: 'skills', type: 'system' })
    }

    async buildEquipment() {
      let weapons = this.actor.items.filter(item => item.type === 'weapon')
      let skills = this.actor.items.filter(item => item.type === 'skill')
      for (const item of weapons) {
        // Push the weapon name as a new group
        const groupData = {
          id: 'weapons_' + item._id,
          name: item.name,
          type: 'system'
        }
        if (!SYSTEM.WEAPON_SKILL_MAPPING[era] || !SYSTEM.WEAPON_SKILL_MAPPING[era][options.rollItem.system.weaponType]) {
          continue
        }
        let skillName = game.i18n.localize(SYSTEM.WEAPON_SKILL_MAPPING[era][options.rollItem.system.weaponType])
        let skill = skills.find(skill => skill.name.toLowerCase() === skillName.toLowerCase())
        this.addGroup(groupData, { id: 'weapons', type: 'system' }, true)
        if (item.type === 'weapon') {
          const weapons = []
          const tooltip = {
            content: String(skill.system.computeScore()),
            direction: 'LEFT'
          }
          weapons.push({
            name: skill.name,
            id: skill._id,
            info1: this.#showValue() ? { text: tooltip.content } : null,
            encodedValue: ['weapons', item._id].join(this.delimiter),
            tooltip
          })
          const damageTooltip = {
            content: String(item.system.damage),
            direction: 'LEFT'
          }
          if (item.system.damage !== '') {
            weapons.push({
              name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.Damage'),
              id: item._id,
              info1: this.#showValue() ? { text: damageTooltip.content } : null,
              encodedValue: ['damage', item._id].join(this.delimiter),
              tooltip: damageTooltip
            })
          }
          if (item.system.isLethal) {
            const lethalityTooltip = {
              content: String(item.system.lethality),
              direction: 'LEFT'
            }
            weapons.push({
              name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.Lethality'),
              id: item._id,
              info1: this.#showValue() ? { text: lethalityTooltip.content } : null,
              encodedValue: ['lethality', item._id].join(this.delimiter),
              tooltip: lethalityTooltip
            })
          }
          await this.addActions(weapons, {
            id: 'weapons_' + item._id,
            type: 'system'
          })
        }/* else if (item.type === 'ritual') {
                    rituals.push({
                        name: item.name,
                        id: item._id,
                        encodedValue: ['rituals', item.name].join(this.delimiter)
                    })
                } */

        /* await this.addActions(rituals, {
            id: 'rituals',
            type: 'system'
        }) */
      }
    }

    /**
     * Build multiple token actions
     * @private
     * @returns {object}
     */
    #buildMultipleTokenActions() {
    }
  }
})
