/* Copyright 2022 Jaakko Keränen <jaakko.keranen@iki.fi>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "events.h"
#include "render.h"
#include "video.h"
#include "SDL_timer.h"
#include "SDL_keyboard.h"

#include <the_Foundation/mutex.h>
#include <the_Foundation/string.h>
#include <the_Foundation/vec2.h>
#include <ctype.h>

iDeclareType(EventQueue)

#define MAX_EVENTS  1024

struct Impl_EventQueue {
    iMutex *mtx;
    SDL_Event events[MAX_EVENTS];
    int head, tail;
};

static void init_EventQueue(iEventQueue *d) {
    d->mtx = new_Mutex();
    d->head = d->tail = 0;
}

static void deinit_EventQueue(iEventQueue *d) {
    delete_Mutex(d->mtx);
}

static void push_EventQueue(iEventQueue *d, const SDL_Event *ev) {
    lock_Mutex(d->mtx);
    d->events[d->head++] = *ev;
    d->head %= MAX_EVENTS;
    iAssert(d->head != d->tail);
    unlock_Mutex(d->mtx);
}

static iBool poll_EventQueue(iEventQueue *d, SDL_Event *ev) {
    lock_Mutex(d->mtx);
    iBool ok = iFalse;
    if (d->head != d->tail) {
        *ev = d->events[d->tail++];
        d->tail %= MAX_EVENTS;
        ok = iTrue;
    }
    unlock_Mutex(d->mtx);
    return ok;
}

iDefineTypeConstruction(EventQueue)

/*----------------------------------------------------------------------------------------------*/

static iEventQueue *queue_;

static void postWindowSizeChanged_(void) {
    const iInt2 size = SDL_QueryTerminalSize();
    endwin();
    werase(currentWindow_Video->cwin);
    resize_term(size.y, size.x);
    SDL_ResizeWindow(currentWindow_Video, size.x, size.y);
    SDL_WindowEvent resized = { .type      = SDL_WINDOWEVENT,
                                .timestamp = SDL_GetTicks(),
                                .event     = SDL_WINDOWEVENT_RESIZED,
                                .data1     = size.x,
                                .data2     = size.y };
    SDL_PushEvent((SDL_Event *) &resized);
}

void SDL_InitEvents(void) {
    queue_ = new_EventQueue();
}

void SDL_QuitEvents(void) {
    delete_EventQueue(queue_);
    queue_ = NULL;
}

void SDL_PushEvent(const SDL_Event *ev) {
    push_EventQueue(queue_, ev);
}

void SDL_SendKeyboardPress(int sym, int mods) {
    if (sym == SDLK_BACKSPACE && mods == KMOD_ALT) {
        mods = KMOD_CTRL; /* M-Backspace produces ^Backspace */
    }
//    printf("key:%x(%c)\n\r", sym, (char)sym);
    SDL_KeyboardEvent ev = { .type      = SDL_KEYDOWN,
                             .timestamp = SDL_GetTicks(),
                             .state     = SDL_PRESSED };
    ev.keysym.sym = sym;
    ev.keysym.mod = mods;
    SDL_PushEvent((SDL_Event *) &ev);
    /* Release the key, too. */
    ev.type = SDL_KEYUP;
    ev.state = SDL_RELEASED;
    SDL_PushEvent((SDL_Event *) &ev);
}

void SDL_EventState(int event, int state) {}

void SDL_AddEventWatch(int (*filter)(void *, SDL_Event *), void *userdata) {}

void SDL_DelEventWatch(int (*filter)(void *, SDL_Event *), void *userdata) {}

void SDL_PumpEvents(void) {
    if (!currentWindow_Video) {
        return;
    }
    WINDOW *cwin = currentWindow_Video->cwin;
    iString buf;
    init_String(&buf);
    iBool isMeta = iFalse;
    for (;;) {
        int c = wgetch(cwin);
        if (c == ERR) break;
//        printf("c=%o\n\r", c);
        if (c == KEY_RESIZE) {
            postWindowSizeChanged_();
        }
        else if (c & KEY_CODE_YES || c & 01000) {
            /* TODO: translate to SDLK codes */
            static const struct {
                int ckey;
                int sdlk;
                int mod;
            } keyMap[] = {
                { KEY_BACKSPACE, SDLK_BACKSPACE },
                { KEY_DC, SDLK_DELETE },
                { KEY_UP, SDLK_UP },
                { KEY_DOWN, SDLK_DOWN },
                { KEY_LEFT, SDLK_LEFT },
                { KEY_RIGHT, SDLK_RIGHT },
                { KEY_NPAGE, SDLK_PAGEDOWN },
                { KEY_PPAGE, SDLK_PAGEUP },
                { KEY_HOME, SDLK_HOME },
                { KEY_END, SDLK_END },
                { KEY_BTAB, SDLK_TAB, KMOD_SHIFT },
                { KEY_F(1), SDLK_F1 },
                { KEY_F(2), SDLK_F2 },
                { KEY_F(3), SDLK_F3 },
                { KEY_F(4), SDLK_F4 },
                { KEY_F(5), SDLK_F5 },
                { KEY_F(6), SDLK_F6 },
                { KEY_F(7), SDLK_F7 },
                { KEY_F(8), SDLK_F8 },
                { KEY_F(9), SDLK_F9 },
                { KEY_F(10), SDLK_F10 },
                { KEY_F(11), SDLK_F11 },
                { KEY_F(12), SDLK_F12 },
                { KEY_SLEFT, SDLK_LEFT, KMOD_SHIFT },
                { KEY_SRIGHT, SDLK_RIGHT, KMOD_SHIFT },
                { KEY_SR, SDLK_UP, KMOD_SHIFT },
                { KEY_SF, SDLK_DOWN, KMOD_SHIFT },
                { KEY_SHOME, SDLK_HOME, KMOD_SHIFT },
                { KEY_SEND, SDLK_END, KMOD_SHIFT },
                { 01030, SDLK_HOME, KMOD_CTRL },
                { 01031, SDLK_HOME, KMOD_CTRL | KMOD_SHIFT },
                { 01023, SDLK_END, KMOD_CTRL },
                { 01024, SDLK_END, KMOD_CTRL | KMOD_SHIFT },
                { 01042, SDLK_LEFT, KMOD_CTRL },
                { 01043, SDLK_LEFT, KMOD_CTRL | KMOD_SHIFT },
                { 01046, SDLK_LEFT, KMOD_CTRL },
                { 01047, SDLK_LEFT, KMOD_CTRL | KMOD_SHIFT },
                { 01061, SDLK_RIGHT, KMOD_CTRL },
                { 01062, SDLK_RIGHT, KMOD_CTRL | KMOD_SHIFT },
                { 01065, SDLK_RIGHT, KMOD_CTRL },
                { 01066, SDLK_RIGHT, KMOD_CTRL | KMOD_SHIFT },
                { 01067, SDLK_UP, KMOD_CTRL },
                { 01070, SDLK_UP, KMOD_CTRL | KMOD_SHIFT },
                { 01016, SDLK_DOWN, KMOD_CTRL },
                { 01017, SDLK_DOWN, KMOD_CTRL | KMOD_SHIFT },
            };
            // printf("c=%0d\n", c); fflush(stdout);
            iForIndices(i, keyMap) {
                if (keyMap[i].ckey == c) {
                    SDL_SendKeyboardPress(keyMap[i].sdlk, keyMap[i].mod | (isMeta ? KMOD_ALT : 0));
                    break;
                }
            }
            isMeta = iFalse;
        }
        else if (c == 0x1b) {
            isMeta = iTrue;
        }
        else if (c == '\t') {
            SDL_SendKeyboardPress(SDLK_TAB, isMeta ? KMOD_ALT : 0);
            isMeta = iFalse;
        }
        else if (c == 13) {
            SDL_SendKeyboardPress(SDLK_RETURN, isMeta ? KMOD_ALT : 0);
            isMeta = iFalse;
        }
        else if (c == 7) {
            /* Ctrl+G is an Emacs-like cancel. */
            SDL_SendKeyboardPress(SDLK_ESCAPE, 0);
        }
        else if (c < 0x20) {
            if (c == 4) {
                SDL_SendKeyboardPress(SDLK_DELETE, isMeta ? KMOD_ALT : 0);
            }
            else {
                SDL_SendKeyboardPress(SDLK_a + c - 1, KMOD_CTRL | (isMeta ? KMOD_ALT : 0));
            }
            isMeta = iFalse;
        }
        else if (c == 127) {
            SDL_SendKeyboardPress(SDLK_BACKSPACE, isMeta ? KMOD_ALT : 0);
            isMeta = iFalse;
        }
        else {
            pushBack_Block(&buf.chars, c);
            if (isUtf8_Rangecc(range_String(&buf))) {
                if (SDL_IsTextInputStarted() && (!isMeta || c >= 127)) {
                    SDL_TextInputEvent inp = {
                        .type = SDL_TEXTINPUT,
                        .timestamp = SDL_GetTicks()
                    };
                    strncpy(inp.text, cstr_String(&buf), sizeof(inp.text) - 1);
                    SDL_PushEvent((SDL_Event *) &inp);
                }
                else {
                    int mod = 0;
                    if (isupper(iMin(127, c))) {
                        c = lower_Char(c);
                        mod = KMOD_SHIFT;
                    }
                    if (isMeta) {
                        mod |= KMOD_ALT;
                        isMeta = iFalse;
                    }
                    SDL_SendKeyboardPress(c, mod);
                }
                clear_String(&buf);
            }
        }
    }
    if (isMeta) {
        /* A meta combo did not follow. */
        SDL_SendKeyboardPress(SDLK_ESCAPE, 0);
    }
    deinit_String(&buf);
}

int SDL_WaitEvent(SDL_Event *event) {
    return SDL_WaitEventTimeout(event, 0xffffffff);
}

static void updateKeyModState_(const SDL_Event *ev) {
    if (ev->type == SDL_KEYDOWN) {
        SDL_SetModState(ev->key.keysym.mod);
    }
    else if (ev->type == SDL_KEYUP) {
        SDL_SetModState(0);
    }
}

static int doPoll_(SDL_Event *event) {
    SDL_PumpEvents();
    event->type = 0;
    const int gotEvent = poll_EventQueue(queue_, event);
    if (gotEvent) {
        updateKeyModState_(event);
    }
    return gotEvent;
}

int SDL_PollEvent(SDL_Event *event) {
    nodelay(currentWindow_Video->cwin, true);
    return doPoll_(event);
}

int SDL_WaitEventTimeout(SDL_Event *event, uint32_t timeout) {
    if (SDL_PollEvent(event)) {
        /* Got something already, so no waiting required. */
        return SDL_TRUE;
    }
    /* TODO: If we do respect `timeout`, pushing an SDL_Event in the queue will need to also
       ungetch() a fake key to wake up the curses key listener. */
    wtimeout(currentWindow_Video->cwin, 1000 / 60);
    return doPoll_(event);
}
