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

/* -------------------------------------------- */
export class MournbladeCYD2TokenHud {

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

  /* -------------------------------------------- */
  static async removeExtensionHud(app, html, tokenId) {
    html.find('.control-icon.mournblade-cyd2-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 MournbladeCYD2TokenHud._configureSubMenu(controlIconActions, 'systems/fvtt-mournblade-cyd2/templates/hud-adversites.html', 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 ) {
      MournbladeCYD2TokenHud.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.mournblade-cyd2-hud-list')

    MournbladeCYD2TokenHud._toggleHudListActive(hud, list);

    hud.find('img.mournblade-cyd2-hud-togglebutton').click(event => MournbladeCYD2TokenHud._toggleHudListActive(hud, list));
    list.find('.mournblade-cyd2-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')
    MournbladeCYD2TokenHud._showControlWhen(list, hud.hasClass('active'))
  }
}