let effect = args[0];
let targets = args[1];
let extra = args[2];
if (!extra) {
    extra = {};
}
if (!extra.name) { extra.name = effect.label }
if (!extra.duration) { extra.duration = effect.duration?.rounds }
if (!extra.startMessage) {
    extra.startMessage = `${effect.label}'s effects start`
}
if (!extra.endMessage) {
    extra.endMessage = `${effect.label}'s effects end`
}
if (!extra.fadeMessage) {
    extra.fadeMessage = `${effect.label}'s effects start to fade`
}

if (canvas.tokens.controlled.length == 0) {
    ui.notifications.error("No tokens selected");
    return;
}
for (let tgt of targets) {
    let actor = tgt.actor;
    let active = actor.effects.find(i => i.data.label === effect.label);
    let chatData = {
        speaker: ChatMessage.getSpeaker(tgt),
        type: CONST.CHAT_MESSAGE_TYPES.OTHER,
        emote: true
    }
    if (extra.flavor) {
        chatData.flavor = extra.flavor;
    }
    if (active) {
        await tgt.toggleEffect(effect, { active: false })
        chatData.content = extra.endMessage;
    } else {
        await tgt.toggleEffect(effect, { active: true })
        chatData.content = extra.startMessage;
    }
    if (chatData.content) {
        ChatMessage.create(chatData);
    }
}
if (game.modules.get("turnAlert")?.active) {
    if (game.combat && extra.duration) {
        let alertData = {
            round: extra.duration - 1,
            roundAbsolute: false,
            turnId: game.combat.combatant._id,
            message: extra.fadeMessage
        }
        await TurnAlert.create(alertData);

        const targetIds = targets.map(t => t.id);
        alertData = {
            round: extra.duration - 1,
            roundAbsolute: false,
            turnId: game.combat.combatant._id,
            endOfTurn: true,
            message: extra.endMessage,
            macro: "CancelSpellEffect",
            args: [effect, targetIds]
        }
        await TurnAlert.create(alertData);
    }
} else if (game.modules.get("about-time")?.active && extra.duration) {
    let duration = extra.duration * 6;
    let preDuration = duration - 6;
    console.log("effects end in duration:", duration, preDuration)
    Gametime.doIn({ seconds: preDuration }, () => {
        let chatData = {
            type: CONST.CHAT_MESSAGE_TYPES.OTHER,
            emote: true,
            content: extra.fadeMessage
        }
        if (extra.flavor) {
            chatData.flavor = extra.flavor;
        }
        ChatMessage.create(chatData);
    });
    const targetIds = targets.map(t => t.id);
    Gametime.doIn({ seconds: duration }, () => {
        let chatData = {
            type: CONST.CHAT_MESSAGE_TYPES.OTHER,
            emote: true,
            content: extra.endMessage
        }
        if (extra.flavor) {
            chatData.flavor = extra.flavor;
        }
        ChatMessage.create(chatData);
        let macro = game.macros.getName("CancelSpellEffect")
        macro.execute(effect, targetIds)
    })
}
