import { MGT2Helper } from "./helper.js";

export class ChatHelper {

    static setupCardListeners(message, element, messageData) {
        if (!message || !element) {
            return;
        }
        element.querySelectorAll('button[data-action="rollDamage"]').forEach(el => {
            el.addEventListener('click', async event => {
                await this._processRollDamageButtonEvent(message, event);
            });
        });

        element.querySelectorAll('button[data-action="damage"]').forEach(el => {
            el.addEventListener('click', async event => {
                await this._applyChatCardDamage(message, event);
            });
        });

        element.querySelectorAll('button[data-action="healing"]').forEach(el => {
            el.addEventListener('click', async event => {
                ui.notifications.warn("healing");
            });
        });

        element.querySelectorAll('button[data-index]').forEach(el => {
            el.addEventListener('click', async event => {
                await this._processRollButtonEvent(message, event);
            });
        });
    }

    static async _processRollButtonEvent(message, event) {
        event.preventDefault();
        event.stopPropagation();
        let buttons = message.flags.mgt2.buttons;
        const index = event.target.dataset.index;
        const button = buttons[index];
        let roll = await new Roll(button.formula, {}).roll();

        const chatData = {
            user: game.user.id,
            speaker: message.speaker,
            formula: roll._formula,
            tooltip: await roll.getTooltip(),
            total: Math.round(roll.total * 100) / 100,
            rollObjectName: button.message.objectName,
            rollMessage: MGT2Helper.format(button.message.flavor, Math.round(roll.total * 100) / 100),
          };

          const html = await foundry.applications.handlebars.renderTemplate("systems/mgt2/templates/chat/roll.html", chatData);
          chatData.content = html;
          return roll.toMessage(chatData);
    }

    static async _processRollDamageButtonEvent(message, event) {
        event.preventDefault();
        event.stopPropagation();
        let rollFormula = message.flags.mgt2.damage.formula;

        let roll = await new Roll(rollFormula, {}).roll();

        let speaker;
        let selectTokens = canvas.tokens.controlled;
        if (selectTokens.length > 0) {
            speaker = selectTokens[0].actor;
        } else {
            speaker = game.user.character;
        }

        let rollTypeName = message.flags.mgt2.damage.rollTypeName ? message.flags.mgt2.damage.rollTypeName + " DAMAGE" : null;

        const chatData = {
            user: game.user.id,
            speaker: ChatMessage.getSpeaker({ actor: speaker }),
            formula: roll._formula,
            tooltip: await roll.getTooltip(),
            total: Math.round(roll.total * 100) / 100,
            showButtons: true,
            hasDamage: true,
            rollTypeName: rollTypeName,
            rollObjectName: message.flags.mgt2.damage.rollObjectName
        };

        const html = await foundry.applications.handlebars.renderTemplate("systems/mgt2/templates/chat/roll.html", chatData);
        chatData.content = html;

        return roll.toMessage(chatData);
    }

    static _applyChatCardDamage(message, event) {
        const roll = message.rolls[0];
        return Promise.all(canvas.tokens.controlled.map(t => {
            const a = t.actor;
            return a.applyDamage(roll.total);
        }));
    }
}