const ICON = 'systems/swade/assets/icons/status/status_protection.svg'

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: "Protection",
        content: `Apply <em>Protection</em> to ${tokenList}`,
        default: "cancel",
        buttons: [
            {label: "Apply (+2 armor)", value: "apply"},
            {label: "Apply with raise (+2 toughness)", 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 = 'Protection';
    let effectId = 'protection';
    const effectIcon = ICON;
    let changes = [
        {
            key: 'data.stats.toughness.armor',
            mode: foundry.CONST.ACTIVE_EFFECT_MODES.UPGRADE,
            value: 2,
            priority: 0
        }
    ];
    if (choice == 'raise') {
        changes[0].key = 'data.stats.toughness.value';
    }
    for (const token of tokens) {
        let effectData = {
            icon: effectIcon,
            id: effectId,
            label: effectName,
            duration: {rounds: 5},
            flags: {
                swade: {
                    expiration: 3,
                    loseTurnOnHold: true
                }
            },
            changes: changes,
        };
        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);
    }
}