const ICON = 'icons/magic/defensive/shield-barrier-deflect-teal.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 dialogOptions = {
        title: "Deflection",
        content: `Apply <em>Deflection</em> to ${tokenList}`,
        default: "cancel",
        buttons: [
            {label: "Apply (melee)", value: "melee"},
            {label: "Apply (ranged)", value: "ranged"},
            {label: "Apply with raise (both)", value: "raise"},
            {label: "Cancel", value: "cancel"}
        ]
    }
    let choice = await warpgate.buttonDialog(dialogOptions);
    if (choice != "cancel") {
        createEffect(tokens, choice);
    }
}

async function createEffect(tokens, choice) {
    let effectName = 'Deflection';
    let effectId = `deflection${choice}`;
    let changes = []
    switch (choice) {
        case 'melee':
            effectName = "Melee " + effectName;
            break
        case 'ranged':
            effectName = "Ranged " + effectName;
            break 
    }
    const effectIcon = ICON;
    for (const token of tokens) {
        let effectData = {
            icon: effectIcon,
            id: effectId,
            label: effectName,
            duration: {rounds: 5},
            flags: {
                swade: {
                    expiration: 3,
                    loseTurnOnHold: true
                }
            },
            changes: [
                {key: 'data.stats.parry.modifier', mode: foundry.CONST.ACTIVE_EFFECT_MODES.UPGRADE, value: 0, 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);
    }
}