const ICON = 'icons/magic/control/modfiy-luck-fortune-gray.webp'

const PACKNAMES = [
    'swade-core-rules.swade-edges',
    'swpf-core-rules.swpf-edges',
]

const EDGENAMES = [
    'Block',
    'Improved Block',
    'Brawler',
    'Bruiser',
    'Calculating',
    'Combat Reflexes',
    'Counterattack',
    'Improved Counterattack',
    'Dead Shot',
    'Dodge',
    'Extraction',
    'Improved Extraction',
    'Feint',
    'First Strike',
    'Improved First Strike',
    'Formation Fighter',
    'Free Runner',
    'Frenzy',
    'Improved Frenzy',
    'Giant Killer',
    'Hard to Kill',
    'Harder to Kill',
    'Improvisational Fighter',
    'Iron Jaw',
    'Killer Instinct',
    'Level Headed',
    'Improved Level Headed',
    'Marksman',
    'Mighty Blow',
    'Nerves of Steel',
    'Improved Nerves of Steel',
    'No Mercy',
    'Rapid Reload',
    'Rapid Shot',
    'Improved Rapid Shot',
    'Steady Hands',
    'Sweep',
    'Improved Sweep',
    'Trademark Weapon',
    'Improved Trademark Weapon',
    'Two-Weapon Fighting',
]

let EDGES = new Map()
for (let edgeName of EDGENAMES) {
    for (let packName of PACKNAMES) {
        let edge = game.packs.get(packName)?.index?.find(i => i.name == edgeName);
        if (edge) {
            EDGES.set(edgeName, {pack: packName, edge: edge._id});
            break;
        }
    }
}

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: "Warrior's Gift",
        defaultButton: "cancel",
        options: {}
    }
    let edgeNames = Array.from(EDGES.keys()).sort();
    let menuData = {
        inputs: [
            {type: 'header', label: "Warrior's Gift"},
            {type: 'info', label: `Apply Warrior's Gift to ${tokenList}`},
            {type: 'select', label: "Edge", options: edgeNames},
        ],
        buttons: [
            {label: "Apply", value: "apply"},
            {label: "Cancel", value: "cancel"}
        ]
    }
    let {buttons, inputs} = await warpgate.menu(menuData, menuOptions);
    if (buttons && buttons != "cancel") {
        await createEffect(tokens, inputs[2]);
    }
}

async function createEffect(tokens, edgeName) {
    const effectIcon = ICON;
    for (const token of tokens) {
        const effectName = `Warrior's Gift (${edgeName})`;
        const effectId = `warriorsgift${edgeName}`;
        const edgeId = EDGES.get(edgeName).edge;
        const pack = EDGES.get(edgeName).pack;
        const edge = await game.packs.get(pack).getDocument(edgeId);
        let effectData = {
            icon: effectIcon,
            id: effectId,
            label: effectName,
            duration: {rounds: 5},
            flags: {
                swade: {
                    expiration: 3,
                    loseTurnOnHold: true
                }
            },
            changes: [],
        };
        let edgeData = {...edge.data};
        let mutate = {
            embedded: {
                Item: {
                    [edgeName]: edgeData,
                },
                ActiveEffect: {
                    [effectName]: effectData,
                }
            }
        };
        edgeData.effects.forEach(edgeEffect => {
            mutate.embedded.ActiveEffect[edgeEffect.data.label] = edgeEffect.data
        })
        
        let mutateOptions = {
            comparisonKeys: {'ActiveEffect': 'label'},
            name: effectName,
            permanent: false,
            description: effectName,
        }
        await warpgate.mutate(token.document, mutate, {}, mutateOptions);
    }
}