const ICON = 'icons/weapons/swords/sword-flanged-lightning.webp'

let tokens = [];
let targets = Array.from(game.user.targets);
if (targets.length > 0) {
    tokens = targets;
} else if (canvas.tokens.controlled.length > 0) {
    tokens = canvas.tokens.controlled;
}
if (tokens.length > 0) {
    main(tokens);
} else {
    ui.notifications.error("Please select or target a token");
}

async function main(tokens) {
    let tokenList = tokens.map(t => t.name).join(", ");
    let menuOptions = {
        title: 'Smite',
        defaultButton: "cancel",
        options: {}
    }
    let menuData = {
        inputs: [
            {type: 'header', label: 'Smite'},
            {type: 'info', label: `Apply Smite to ${tokenList}`},
        ],
        buttons: [
            {label: "Apply", value: "apply"},
            {label: "Apply with Raise", value: "raise"},
            {label: "Cancel", value: "cancel"}
        ]
    }
    let tokenWeapons = {};
    let index = 1;
    for (const token of tokens) {
        index += 2;
        tokenWeapons[token.id] = index;
        menuData.inputs.push({type: 'info', label: `<h2>${token.name}</h2>`});
        let weapons = token.actor.items.filter(i => i.type == 'weapon').map(i => i.name);
        weapons.unshift("");
        menuData.inputs.push({type: 'select', label: token.name, options: weapons});
    }
    let {buttons, inputs} = await warpgate.menu(menuData, menuOptions);
    for (let tokenid in tokenWeapons) {
        tokenWeapons[tokenid] = inputs[tokenWeapons[tokenid]];
    }
    if (buttons != "cancel") {
        await createEffect(tokens, tokenWeapons, buttons);
    }
    console.log(buttons, tokenWeapons);
}

async function createEffect(tokens, tokenWeapons, choice) {
    const effectIcon = ICON;
    const changeValue = (choice == 'raise' ? "+4" : "+2");
    for (const token of tokens) {
        const weaponName = tokenWeapons[token.id];
        const weaponId = token.actor.items.getName(weaponName)?.id
        const changeKey = `@Weapon{${weaponName}}[data.damage]`
        if (!weaponId) {
            continue
        }
        const effectName = `Smite (${weaponName})`;
        const effectId = `smite${choice}_${weaponId}`;
        let effectData = {
            icon: effectIcon,
            id: effectId,
            label: effectName,
            duration: {rounds: 5},
            flags: {
                swade: {
                    expiration: 3,
                    loseTurnOnHold: true
                }
            },
            changes: [
                {
                    key: changeKey,
                    mode: foundry.CONST.ACTIVE_EFFECT_MODES.ADD,
                    value: changeValue,
                    priority: 0
                }
            ],
        };
        let mutate = {
            embedded: {
                ActiveEffect: {
                }
            }
        };
        mutate.embedded.ActiveEffect[effectName] = effectData;
        let mutateOptions = {
            comparisonKeys: {'ActiveEffect': 'label'},
            name: effectName,
            permanent: true,
            description: effectName,
        }
        await warpgate.mutate(token.document, mutate, {}, mutateOptions);
    }
}