// System Module Imports
import CthulhuEternalUtils from '../../utils.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) {
      // this.actor and this.actors are provided by the base class (TAH Core v2+)
      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.actor) {
        if (this.actorType !== 'vehicle') {
          this.#buildCharacterActions()
        }
      } else {
        this.#buildMultipleTokenActions()
      }
    }

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

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

    async buildCharacteristics() {
      const actions = []
      for (const key in this.actor.system.characteristics) {
        const encodedValue = ['characteristics', 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: 'characteristics',
        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: ['characteristics', 'luck'].join(this.delimiter)
      })
      await this.addActions(actions, { id: 'luck', type: 'system' })
    }

    async buildOther() {
      if (typeof this.actor.system?.san?.value !== 'undefined') {
        const actions = []
        const groupData = {
          id: 'other_san',
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.SAN'),
          type: 'system'
        }
        this.addGroup(groupData, { id: 'other', type: 'system' }, true)
        const tooltip = {
          content: `${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: 'san',
          info1: this.#showValue() ? { text: tooltip.content } : null,
          tooltip,
          encodedValue: ['characteristics', 'san'].join(this.delimiter)
        },
          {
            name: '+',
            id: 'san_add',
            tooltip,
            encodedValue: ['characteristics', 'san_add'].join(this.delimiter)
          },
          {
            name: '-',
            id: 'san_subtract',
            tooltip,
            encodedValue: ['characteristics', 'san_subtract'].join(this.delimiter)
          })
        await this.addActions(actions, { id: 'other_san', type: 'system' })
      }
      if (typeof this.actor.system.hp.value !== 'undefined') {
        const actions = []
        const groupData = {
          id: 'other_hp',
          name: coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.HP'),
          type: 'system'
        }
        this.addGroup(groupData, { id: 'other', type: 'system' }, true)
        const tooltip = {
          content: `${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: 'hp',
          info1: this.#showValue() ? { text: tooltip.content } : null,
          tooltip,
          encodedValue: ['characteristics', 'hp'].join(this.delimiter)
        },
          {
            name: '+',
            id: 'hp_add',
            tooltip,
            encodedValue: ['characteristics', 'hp_add'].join(this.delimiter)
          },
          {
            name: '-',
            id: 'hp_subtract',
            tooltip,
            encodedValue: ['characteristics', 'hp_subtract'].join(this.delimiter)
          })
        await this.addActions(actions, { id: 'other_hp', 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: `${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: ['characteristics', 'wp'].join(this.delimiter)
        },
          {
            name: '+',
            id: 'wp_add',
            tooltip,
            encodedValue: ['characteristics', 'wp_add'].join(this.delimiter)
          },
          {
            name: '-',
            id: 'wp_subtract',
            tooltip,
            encodedValue: ['characteristics', 'wp_subtract'].join(this.delimiter)
          })
        await this.addActions(actions, { id: 'other_wp', type: 'system' })
      }
    }

    async buildSkills() {
      const actions = []
      // Build alpha sorted skill list
      let skills = this.actor.items.filter(i => i.type === 'skill')
      skills = skills.sort((a, b) => a.name.localeCompare(b.name))

      for (const skill of skills) {
        //console.log('Processing skill item:', skill)
        if (skill.system.skillTotal > 0) {
          const tooltip = {
            content: String(skill.system.skillTotal),
            direction: 'LEFT'
          }
          actions.push({
            name: `${skill.name} (${skill.system.skillTotal})`,
            id: skill.id,
            info1: this.#showValue() ? { text: tooltip.content } : null,
            tooltip,
            encodedValue: ['skills', skill.id].join(this.delimiter)
          })
        }
      }
      await this.addActions(actions, { id: 'skills', type: 'system' })
    }

    async buildEquipment() {
      let era = game.settings.get("fvtt-cthulhu-eternal", "settings-era")

      const weapons = this.actor.items.filter(i => i.type === 'weapon')
      for (const item of weapons) {
        // Push the weapon name as a new group
        const groupData = {
          id: `weapons_${item._id}`,
          name: item.name,
          type: 'system'
        }
        this.addGroup(groupData, { id: 'weapons', type: 'system' }, true)
          let skill = CthulhuEternalUtils.getWeaponSkill(this.actor, item, era)
          item.skillTotal = skill ? skill.system.skillTotal : 0
          let weaponActions = []
          const tooltip = {
            content: String(item.skillTotal),
            direction: 'LEFT'
          }
          weaponActions.push({
            name: `${item.name} (${item.skillTotal})`,
            id: `weapon_${item._id}`,
            info1: this.#showValue() ? { text: tooltip.content } : null,
            encodedValue: ['weapons', item._id].join(this.delimiter),
            tooltip
          })
          let damage = ''
          if (item.system.lethality > 0) {
            damage = `L:${item.system.lethality}%`
          } else {
            damage = item.system.damage
          }
          const damageTooltip = {
            content: String(damage),
            direction: 'LEFT'
          }
          if (item.system.damage !== '') {
            weaponActions.push({
              name: `${coreModule.api.Utils.i18n('CTHULHUETERNAL.Label.Damage')} (${damage})`,
              id: `damage_${item._id}`,
              info1: this.#showValue() ? { text: damageTooltip.content } : null,
              encodedValue: ['damage', item._id].join(this.delimiter),
              tooltip: damageTooltip
            })
          }
          await this.addActions(weaponActions, {
            id: `weapons_${item._id}`,
            type: 'system'
          })
      }
    }

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