#include <windows.h>
#include <shellapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NAME "dwhkd"

typedef union {
    int i;
    unsigned int ui;
    float f;
    void *v;
} Arg;

#include "debug.h"
#include "actions.h"
#include "config.c"
#include "plugin.h"

static HWND dwmhwnd;
typedef struct {
    char *name;
    HMODULE dll;
    sxhkd_plugin_invoke_fn invoke;
} Plugin;
static Plugin *plugins;
static size_t plugin_count;

static void unload_plugins(void) {
    for (size_t i = 0; i < plugin_count; i++) {
        if (plugins[i].dll) FreeLibrary(plugins[i].dll);
        free(plugins[i].name);
    }
    free(plugins);
    plugins = NULL;
    plugin_count = 0;
}

static int load_plugins(void) {
    if (!binding_count) return 1;
    plugins = calloc(binding_count, sizeof *plugins);
    if (!plugins) return 0;
    char path[MAX_PATH];
    DWORD n = GetModuleFileNameA(NULL, path, sizeof path);
    if (!n || n >= sizeof path) return 0;
    char *slash = strrchr(path, '\\');
    if (!slash) return 0;
    size_t remaining = sizeof path - (slash + 1 - path);
    for (size_t i = 0; i < binding_count; i++) {
        Binding *binding = &bindings[i];
        if (binding->action != PLUGIN) continue;
        size_t j = 0;
        for (; j < plugin_count; j++)
            if (same(binding->plugin_name, plugins[j].name)) break;
        if (j == plugin_count) {
            int length = snprintf(slash + 1, remaining, "plugins\\%s\\plugin.dll", binding->plugin_name);
            if (length < 0 || (size_t)length >= remaining) return 0;
            Plugin *plugin = &plugins[plugin_count++];
            plugin->name = copy_string(binding->plugin_name);
            if (!plugin->name) return 0;
            plugin->dll = LoadLibraryExA(path, NULL,
                LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
            if (!plugin->dll) {
                fprintf(stderr, "Cannot load %s (error %lu)\n", path, GetLastError());
                return 0;
            }
            sxhkd_plugin_abi_fn abi = (sxhkd_plugin_abi_fn)GetProcAddress(plugin->dll, "sxhkd_plugin_abi");
            plugin->invoke = (sxhkd_plugin_invoke_fn)GetProcAddress(plugin->dll, "sxhkd_plugin_invoke");
            if (!abi || !plugin->invoke || abi() != SXHKD_PLUGIN_ABI) {
                fprintf(stderr, "Incompatible plugin: %s\n", path);
                return 0;
            }
        }
        binding->plugin_index = j;
    }
    return 1;
}

#include "actions.c"

static int run_command(const char *command) {
    const char *shell = getenv("COMSPEC");
    if (!shell || !*shell) shell = "cmd.exe";
    char *parameters = malloc(strlen(command) + 4);
    if (!parameters) return -1;
    sprintf(parameters, "/C %s", command);
    HINSTANCE launched = ShellExecuteA(NULL, "open", shell, parameters, NULL, SW_HIDE);
    free(parameters);
    return (INT_PTR)launched > 32 ? 0 : -1;
}

static int run_binding(const Binding *binding) {
    Arg arg = {0};
    switch (binding->action) {
    case PLUGIN: {
        int result = plugins[binding->plugin_index].invoke(binding->plugin_action, binding->plugin_args);
        if (result) fprintf(stderr, "Plugin %s failed: %s\n", binding->plugin_name, binding->plugin_action);
        return result;
    }
    case TOGGLE_EXPLORER: toggleexplorer(&arg); break;
    case CLOSE_WINDOW: killForeground(&arg); break;
    case FORCE_CLOSE_WINDOW: killMacForeground(&arg); break;
    case QUIT: quit(&arg); return 1; /* Do not run later commands after quitting. */
    case TEST: test(&arg); break;
    default: return run_command(binding->command);
    }
    return 0;
}

static void run_sequence(size_t first) {
    unsigned int mod = bindings[first].mod, key = bindings[first].key;
    for (size_t i = first; i < binding_count && bindings[i].mod == mod &&
         bindings[i].key == key; i++)
        if (run_binding(&bindings[i])) break;
}

static LRESULT CALLBACK window_proc(HWND hwnd, UINT message, WPARAM id, LPARAM data) {
    switch (message) {
    case WM_HOTKEY:
        if (id > 0 && id <= binding_count) run_sequence(id - 1);
        return 0;
    case WM_CLOSE:
        DestroyWindow(hwnd);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    default:
        return DefWindowProcA(hwnd, message, id, data);
    }
}

int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int show) {
    char default_path[MAX_PATH];
    const char *path;
    if (__argc > 1) {
        if (__argc != 3 || strcmp(__argv[1], "-c")) {
            MessageBoxA(NULL, "Usage: dwhkd [-c CONFIG_FILE]", NAME, MB_OK | MB_ICONERROR);
            return 1;
        }
        path = __argv[2];
    } else {
        DWORD length = GetEnvironmentVariableA("APPDATA", default_path, sizeof default_path);
        if (!length || length >= sizeof default_path ||
            length + strlen("\\dwhkd\\dwhkdrc") >= sizeof default_path) {
            MessageBoxA(NULL, "APPDATA is unavailable; specify a config with -c.", NAME, MB_OK | MB_ICONERROR);
            return 1;
        }
        strcat(default_path, "\\dwhkd\\dwhkdrc");
        path = default_path;
    }
    if (!load_config(path)) {
        char message[MAX_PATH + 100];
        snprintf(message, sizeof message, "Cannot load %s. See stderr for details.\nUse -c to specify a config file.", path);
        MessageBoxA(NULL, message, NAME, MB_OK | MB_ICONERROR);
        return 1;
    }

    if (!load_plugins()) {
        MessageBoxA(NULL, "Could not load plugin; check stderr for details.", NAME, MB_OK | MB_ICONERROR);
        unload_plugins();
        free_bindings();
        return 1;
    }
    WNDCLASSEXA cls = {0};
    cls.cbSize = sizeof cls;
    cls.lpfnWndProc = window_proc;
    cls.hInstance = instance;
    cls.lpszClassName = NAME;
    if (!RegisterClassExA(&cls)) {
        MessageBoxA(NULL, "Could not register window class.", NAME, MB_OK | MB_ICONERROR);
        unload_plugins();
        free_bindings();
        return 1;
    }
    dwmhwnd = CreateWindowExA(0, NAME, NAME, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, instance, NULL);
    if (!dwmhwnd) {
        MessageBoxA(NULL, "Could not create message window.", NAME, MB_OK | MB_ICONERROR);
        unload_plugins();
        free_bindings();
        return 1;
    }
    for (size_t i = 0; i < binding_count; i++) {
        if (i && bindings[i].mod == bindings[i - 1].mod && bindings[i].key == bindings[i - 1].key)
            continue;
        if (!RegisterHotKey(dwmhwnd, (int)i + 1, bindings[i].mod, bindings[i].key))
            fprintf(stderr, "%s: hotkey %zu unavailable (error %lu)\n", path, i + 1, GetLastError());
    }
    MSG msg;
    while (GetMessageA(&msg, NULL, 0, 0) > 0) {
        TranslateMessage(&msg);
        DispatchMessageA(&msg);
    }
    for (size_t i = 0; i < binding_count; i++) {
        if (i && bindings[i].mod == bindings[i - 1].mod && bindings[i].key == bindings[i - 1].key)
            continue;
        UnregisterHotKey(dwmhwnd, (int)i + 1);
    }
    free_bindings();
    unload_plugins();
    return (int)msg.wParam;
}
