/* -------------------------------------------- */

/* -------------------------------------------- */
export class HawkmoonTokenHud {

  static init() {
    // Integration du TokenHUD
    Hooks.on('renderTokenHUD', (app, html, data) => { HawkmoonTokenHud.addTokenHudExtensions(app, html, data._id) });
  }

  /* -------------------------------------------- */
  static async removeExtensionHud(app, html, tokenId) {
    html.find('.control-icon.hawkmoon-adversite').remove()
  }

  /* -------------------------------------------- */
  static async addExtensionHud(app, html, tokenId) {

    let token = canvas.tokens.get(tokenId)
    let actor = token.actor
    app.hasExtension = true

    const hudData = { actor: actor }

    const controlIconActions = $(html).find('.control-icon[data-action=combat]');
    // initiative
    await HawkmoonTokenHud._configureSubMenu(controlIconActions, 'systems/fvtt-hawkmoon-cyd/templates/hud-adversites.hbs', hudData,
      (event) => {
        let adversite = event.currentTarget.attributes['data-action-index'].value
        let value = Number(event.currentTarget.attributes['data-action-value'].value)
        hudData.actor.incDecAdversite( adversite, value)
      } )
  }

  /* -------------------------------------------- */
  static async addTokenHudExtensions(app, html, tokenId) {
    const controlIconCombat  = $(html).find('.control-icon[data-action=combat]')
    if (controlIconCombat.length>0 ) {
      HawkmoonTokenHud.addExtensionHud(app, html, tokenId);
    }
  }

  /* -------------------------------------------- */
  static async _configureSubMenu(insertionPoint, template, hudData, onMenuItem) {
    const hud = $(await foundry.applications.handlebars.renderTemplate(template, hudData))
    const list = hud.find('div.hawkmoon-hud-list')

    HawkmoonTokenHud._toggleHudListActive(hud, list);

    hud.find('img.hawkmoon-hud-togglebutton').click(event => HawkmoonTokenHud._toggleHudListActive(hud, list));
    list.find('.hawkmoon-hud-adversite').click(onMenuItem);

    insertionPoint.after(hud);
  }

  /* -------------------------------------------- */
  static _showControlWhen(control, condition) {
    if (condition) {
      control.show()
    }
    else {
      control.hide()
    }
  }

  /* -------------------------------------------- */
  static _toggleHudListActive(hud, list) {
    hud.toggleClass('active')
    HawkmoonTokenHud._showControlWhen(list, hud.hasClass('active'))
  }
}