#include "HotkeysManager.h"
#include <vector>

struct Hotkey {
    int vk;
    Modifier mods;
    std::function<void()> callback;
    bool wasPressed = false;
};

static std::vector<Hotkey> g_hotkeys;

static bool IsModifierDown(reshade::api::effect_runtime* rt, Modifier m) {
    if ((int)m & (int)Modifier::Alt && !rt->is_key_down(VK_MENU))    return false;
    if ((int)m & (int)Modifier::Ctrl && !rt->is_key_down(VK_CONTROL)) return false;
    if ((int)m & (int)Modifier::Shift && !rt->is_key_down(VK_SHIFT))   return false;
    return true;
}

void RegisterHotkey(int vk, Modifier mods, std::function<void()> callback) {
    g_hotkeys.push_back({ vk, mods, std::move(callback) });
}

void ProcessHotkeys(reshade::api::effect_runtime* runtime) {
    for (auto& hotkey : g_hotkeys) {
        bool pressed = IsModifierDown(runtime, hotkey.mods) && runtime->is_key_down(hotkey.vk);

        if (pressed && !hotkey.wasPressed) hotkey.callback();

        hotkey.wasPressed = pressed;
    }
}

void SimulateAltEnter() {
    INPUT inputs[4] = {};
    // ALT down
    inputs[0].type = INPUT_KEYBOARD;
    inputs[0].ki.wVk = VK_MENU;
    // ENTER down
    inputs[1].type = INPUT_KEYBOARD;
    inputs[1].ki.wVk = VK_RETURN;
    // ENTER up
    inputs[2].type = INPUT_KEYBOARD;
    inputs[2].ki.wVk = VK_RETURN;
    inputs[2].ki.dwFlags = KEYEVENTF_KEYUP;
    // ALT up
    inputs[3].type = INPUT_KEYBOARD;
    inputs[3].ki.wVk = VK_MENU;
    inputs[3].ki.dwFlags = KEYEVENTF_KEYUP;

    SendInput(4, inputs, sizeof(INPUT));
}

void SimulateAltTab() {
    keybd_event(VK_MENU, 0, 0, 0); // Appuyer sur Alt
    keybd_event(VK_TAB, 0, 0, 0); // Appuyer sur Tab

    keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0); // Relācher Tab
    keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0); // Relācher Alt
}