/* -------------------------------------------- */
import { renderTemplate } from "./constants.js";
import { HtmlUtility } from "./html-utility.js";
import { Misc } from "./misc.js";
import { RdDCombat } from "./combat/rdd-combat.js";
import { OptionsAvancees, ROLL_DIALOG_V2 } from "./settings/options-avancees.js";
import { Targets } from "./combat/targets.js";

/* -------------------------------------------- */
export class RdDTokenHud {

  static init() {
    // Integration du TokenHUD
    Hooks.on('renderTokenHUD', (app, html) => { RdDTokenHud.addTokenHudExtensions(app, html, app.document?.id) });
  }

  /* -------------------------------------------- */
  static async removeExtensionHud(app, html, tokenId) {
    $(html).find('.control-icon.rdd-combat').remove();
    $(html).find('.control-icon.rdd-initiative').remove();
  }

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

    let token = canvas?.tokens?.get(tokenId);
    let actor = token?.actor ?? app.actor;
    app.hasExtension = true;
    // soins
    await RdDTokenHud.addExtensionHudSoins(html, actor);

    if (isCombat) {
      const combatant = game.combat?.combatants?.find(c => c.tokenId == tokenId)
      if (!combatant) return;
      const actor = RdDCombat.getActorCombatant(combatant, { warning: false })
      if (actor) {
        if (OptionsAvancees.isUsing(ROLL_DIALOG_V2)) {
          await RdDTokenHud.addExtensionHudCombatV2(html, combatant, actor, token)
        }
        else {
          const actions = RdDCombat.listActionsActorCombatant(actor)
          // initiative
          await RdDTokenHud.addExtensionHudInit(html, combatant, actions)
          // combat
          await RdDTokenHud.addExtensionHudAttaques(html, combatant, token, actions.filter(it => !it.initOnly))
        }
      }
    }
  }

  static async addExtensionHudCombatV2(html, combatant, actor, token) {
    const isPossession = actor.listActionsPossessions().length > 0;
    const actionsCombat = isPossession ? [] : actor.listActions()
    const ajustements = combatant?.initiative ?
      [
        { label: 'Initiative +1', action: 'delta', value: 1 },
        { label: 'Initiative -1', action: 'delta', value: -1 }
      ] : []
    const autres = [{ label: "Autre action", action: 'autre' }]
    const actions = Misc.indexed([
      ...actionsCombat,
      ...ajustements,
      ...autres
    ])

    const hudData = {
      combatant,
      token,
      isPossession,
      isEntiteNonIncarnee: actor.isEntiteNonIncarnee(),
      actions,
    };
    const hud = $(await renderTemplate('systems/foundryvtt-reve-de-dragon/templates/hud-actor-combat.hbs', hudData))
    $(html).find('div.col.left').append(hud)

    const list = hud.find('div.rdd-hud-list')
    RdDTokenHud.setupHudToggle(hud, list)

    const selectInitiative = list.find('select[name="initiative"]');
    selectInitiative.change(event => {
      const action = actions.find(it => it.index == event.currentTarget.value)
      console.log('select initiative', combatant.id, action)
      if (action) {
        switch (action.action) {
          case 'delta':
            RdDCombat.incDecInit(combatant.id, action.value);
            break
          case 'autre':
            RdDCombat.rollInitiativeAction(combatant.id,
              { label: "Autre action", action: 'autre', system: { initOnly: true, competence: "Autre action" } });
            break
          default:
            RdDCombat.rollInitiativeAction(combatant.id, action)
        }
        selectInitiative.select("")
      }
    })
    list.find('.rdd-attaque-v2').click(event => combatant.actor.rollAttaque(token))
    list.find('.rdd-possession-v2').click(event => combatant.actor.rollPossession())
  }

  static async addExtensionHudInit(html, combatant, actions) {
    const hudData = {
      combatant, actions,
      commandes: [
        { label: "Autre action", command: 'autre' },
        { label: 'Initiative +1', command: 'delta', value: 1 },
        { label: 'Initiative -1', command: 'deltac', value: -1 }]
    };
    const controlIconCombat = $(html).find('.control-icon[data-action=combat]');
    await RdDTokenHud._configureSubMenu(it => controlIconCombat.after(it),
      'systems/foundryvtt-reve-de-dragon/templates/hud-actor-init.hbs',
      hudData,
      (event) => {
        let initCommand = event.currentTarget.attributes['data-command']?.value
        let initCommandValue = Number(event.currentTarget.attributes['data-command-value']?.value ?? 0)
        let combatantId = event.currentTarget.attributes['data-combatant-id']?.value
        if (initCommand) {
          RdDCombat.applyInitiativeCommand(combatantId, initCommand, initCommandValue)
        } else {
          let index = event.currentTarget.attributes['data-action-index'].value
          let action = hudData.actions[index]
          RdDCombat.rollInitiativeAction(combatantId, action)
        }
      })
  }

  static async addExtensionHudAttaques(html, combatant, token, actions) {

    const hudData = { combatant, token, actions, commandes: [] };
    const divColLeft = $(html).find('div.col.left');
    await RdDTokenHud._configureSubMenu(it => divColLeft.append(it),
      'systems/foundryvtt-reve-de-dragon/templates/hud-actor-attaque.hbs',
      hudData,
      (event) => {
        const actionIndex = event.currentTarget.attributes['data-action-index']?.value;
        const action = hudData.actions[actionIndex];
        const possession = action.action == 'possession' ? combatant.actor.getPossession(action.possessionid) : undefined;
        if (possession) {
          combatant.actor.conjurerPossession(possession);
        }
        else {
          combatant.actor.rollArme(action.arme, action.main, token)
        }
      });
  }

  static async addExtensionHudSoins(html, sourceActor) {
    const target = Targets.getTarget({ warn: false });
    if (target?.actor) {
      const hudSoins = { blessures: target.actor.blessuresASoigner() ?? [] };
      if (hudSoins.blessures.length > 0) {
        const controlIconTarget = $(html).find('.control-icon[data-action=combat]');
        await RdDTokenHud._configureSubMenu(it => controlIconTarget.after(it),
          'systems/foundryvtt-reve-de-dragon/templates/hud-actor-soins.hbs',
          hudSoins,
          (event) => {
            const blessureId = event.currentTarget.attributes['data-blessure-id']?.value;
            sourceActor.rollSoins(target.actor, blessureId)
          });
      }
    }
  }

  /* -------------------------------------------- */
  static async addTokenHudExtensions(app, html, tokenId) {
    console.log(`Adding token HUD extensions for token ${tokenId}`);
    let controlIconCombat = $(html).find('.control-icon[data-action=combat]');
    if (!controlIconCombat.length) {
      const colLeft = $(html).find('div.col.left');
      if (!colLeft.length) return;
      controlIconCombat = $(`<button type="button" class="control-icon" data-action="combat" data-tooltip="Actions de combat" aria-label="Actions de combat"><i class="fa-solid fa-crosshairs" inert=""></i></button>`);
      colLeft.append(controlIconCombat);
    }
    controlIconCombat.click(event => {
      const btn = event.currentTarget;
      if (btn.className.includes('active')) {
        btn.classList.remove('active');
        RdDTokenHud.removeExtensionHud(app, html, tokenId);
      } else {
        btn.classList.add('active');
        setTimeout(() => RdDTokenHud.addExtensionHud(app, html, tokenId, true), 200);
      }
    });

    const isCombat = controlIconCombat[0].className.includes('active');
    RdDTokenHud.addExtensionHud(app, html, tokenId, isCombat);
  }

  /* -------------------------------------------- */
  static async _configureSubMenu(callInsertion, template, hudData, onMenuItem) {
    const hud = $(await renderTemplate(template, hudData));
    const list = hud.find('div.rdd-hud-list');

    RdDTokenHud.setupHudToggle(hud, list)

    list.find('.rdd-hud-menu').click(onMenuItem);

    callInsertion(hud);
  }

  static setupHudToggle(hud, list) {
    function toggleHudList(hud, list) {
      hud.toggleClass('active')
      HtmlUtility.showControlWhen(list, hud.hasClass('active'))
    }
    toggleHudList(hud, list)
    $(hud).find('img.rdd-hud-togglebutton').click(event => toggleHudList(hud, list))
  }

}