#include "gl3w.h"
#include "Window.h"
#include "Runtime.h"
#include "BufferPane.h"

#define INITIAL_WIDTH   800
#define INITIAL_HEIGHT  800
#define FONT_SIZE 16

struct
{
    SDL_TimerID timer_id;
    SDL_Keycode keysym;
    bool pressed;
} Key_Statuses[SDL_NUM_SCANCODES];

/**
 * Initialize SDL.
 *
 * @retval true SDL was loaded successfully.
 * @retval false Loading SDL failed.
 */
static bool Initialize_SDL()
{
    static bool initialized = false;

    if (initialized)
    {
        return true;
    }

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0)
    {
        return false;
    }

    atexit(SDL_Quit);

    initialized = true;
    return true;
}

/**
 * Initialize OpenGL.
 *
 * @retval true OpenGL was loaded successfully.
 * @retval false Loading OpenGL failed.
 */
static bool Initialize_OpenGL()
{
    if (gl3wInit() != 0)
    {
        /* Failed to gl3wInit() */
        return false;
    }

    if (!gl3wIsSupported(3, 0))
    {
        /* OpenGL 3.0 is not supported */
        return false;
    }

    glActiveTexture(GL_TEXTURE0);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    return true;
}

/**
 * Create a Window.
 *
 * @retval true The Window was created successfully.
 * @retval false There was an error while creating the Window.
 */
bool Window::create(std::shared_ptr<Buffer> buffer)
{
    if (!Initialize_SDL())
    {
        return false;
    }

    m_window = SDL_CreateWindow(
            APPNAME,
            SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED,
            INITIAL_WIDTH,
            INITIAL_HEIGHT,
            SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (m_window == NULL)
    {
        return false;
    }

    (void)SDL_GL_CreateContext(m_window);

    if (!Initialize_OpenGL())
    {
        return false;
    }

    m_exit_requested = false;

    /* TODO: user configurable font, size */
    std::string font_path = Runtime::find(Runtime::FONT, "DejaVuSansMono");
    if (font_path == "")
    {
        return false;
    }

    m_font = std::make_shared<Font>();
    if (!m_font->load(font_path.c_str(), FONT_SIZE))
    {
        return false;
    }

    m_gl = std::make_shared<GL>();

    m_target_column = 0u; /* TODO: fix */

    glClearColor (0.0, 0.0, 0.0, 0.0);

    m_buffer_pane = std::make_shared<BufferPane>(this, buffer);

    resize();

    return true;
}

/**
 * Run the Window event loop.
 *
 * TODO: make this a static method to support multiple GUI windows.
 */
void Window::run_event_loop()
{
    SDL_Event event;

    while ((!m_exit_requested) && SDL_WaitEvent(&event))
    {
        handle_event(event);
        if (m_redraw_requested)
        {
            m_redraw_requested = false;
            redraw();
        }
    }
}

Uint32 Key_Repeat(Uint32 interval, void * param)
{
    if (Key_Statuses[(uintptr_t)param].pressed)
    {
        SDL_Event event;

        event.user.code = 0;
        event.user.data1 = (void *)(uintptr_t)Key_Statuses[(uintptr_t)param].keysym;
        event.user.data2 = nullptr;
        event.type = SDL_USEREVENT;

        SDL_PushEvent(&event);

        return 25u;
    }
    else
    {
        return 0u;
    }
}

/**
 * Handle a SDL event.
 */
void Window::handle_event(SDL_Event & event)
{
    switch (event.type)
    {
    case SDL_QUIT:
        m_exit_requested = true;
        break;

    case SDL_KEYDOWN:
        m_keymod = event.key.keysym.mod;
        if (event.key.repeat == 0)
        {
            Key_Statuses[event.key.keysym.scancode].pressed = true;
            Key_Statuses[event.key.keysym.scancode].keysym = event.key.keysym.sym;
            Key_Statuses[event.key.keysym.scancode].timer_id = SDL_AddTimer(300, Key_Repeat, (void *)event.key.keysym.scancode);
            handle_keysym(event.key.keysym.sym);
        }
        break;

    case SDL_KEYUP:
        m_keymod = event.key.keysym.mod;
        Key_Statuses[event.key.keysym.scancode].pressed = false;
        if (Key_Statuses[event.key.keysym.scancode].timer_id != 0)
        {
            SDL_RemoveTimer(Key_Statuses[event.key.keysym.scancode].timer_id);
            Key_Statuses[event.key.keysym.scancode].timer_id = 0;
        }
        break;

    case SDL_WINDOWEVENT:
        switch (event.window.event)
        {
        case SDL_WINDOWEVENT_EXPOSED:
            redraw();
            break;
        case SDL_WINDOWEVENT_RESIZED:
            resize();
            redraw();
            break;
        }
        break;

    case SDL_USEREVENT:
        handle_keysym((uint32_t)(uintptr_t)event.user.data1);
        break;

    case SDL_MOUSEWHEEL:
        if (event.wheel.y > 0)
        {
            m_buffer_pane->scroll_window_up(ScrollMode::WHEEL);
        }
        else
        {
            m_buffer_pane->scroll_window_down(ScrollMode::WHEEL);
        }
        break;
    }
}

void Window::handle_keysym(uint32_t keysym)
{
    handle_keyval(get_keyval(keysym));
}

void Window::handle_keyval(uint32_t keyval)
{
    switch (keyval)
    {
    case SDLK_HOME:
        m_buffer_pane->cursor_move(CursorMovement::SOL);
        break;
    case SDLK_END:
        m_buffer_pane->cursor_move(CursorMovement::EOL);
        break;
    case SDLK_RIGHT:
        m_buffer_pane->cursor_move(CursorMovement::RIGHT);
        break;
    case SDLK_LEFT:
        m_buffer_pane->cursor_move(CursorMovement::LEFT);
        break;
    case SDLK_DOWN:
        m_buffer_pane->cursor_move(CursorMovement::DOWN);
        break;
    case SDLK_UP:
        m_buffer_pane->cursor_move(CursorMovement::UP);
        break;
    default:
        if (m_buffer_pane->insert_mode())
        {
            if (keyval == '\033')
            {
                m_buffer_pane->exit_insert_mode();
            }
            else if (keyval < 0xFFu)
            {
                m_buffer_pane->insert_code_point(keyval);
            }
        }
        else
        {
            switch (keyval)
            {
            case '0':
                m_buffer_pane->cursor_move(CursorMovement::SOL);
                break;
            case '$':
                m_buffer_pane->cursor_move(CursorMovement::EOL);
                break;
            case 'A':
                m_buffer_pane->enter_insert_mode(EnterInsertModeMode::END_OF_LINE);
                break;
            case 'G':
                m_buffer_pane->cursor_move(CursorMovement::LAST_LINE);
                break;
            case 'I':
                m_buffer_pane->enter_insert_mode(EnterInsertModeMode::START_OF_LINE);
                break;
            case 'O':
                m_buffer_pane->enter_insert_mode(EnterInsertModeMode::NEW_LINE_BEFORE);
                break;
            case 'a':
                m_buffer_pane->enter_insert_mode(EnterInsertModeMode::END_OF_CHAR);
                break;
            case 'g':
                m_buffer_pane->cursor_move(CursorMovement::FIRST_LINE);
                break;
            case 'h':
                m_buffer_pane->cursor_move(CursorMovement::LEFT);
                break;
            case 'i':
                m_buffer_pane->enter_insert_mode(EnterInsertModeMode::START_OF_CHAR);
                break;
            case 'j':
                m_buffer_pane->cursor_move(CursorMovement::DOWN);
                break;
            case 'k':
                m_buffer_pane->cursor_move(CursorMovement::UP);
                break;
            case 'l':
                m_buffer_pane->cursor_move(CursorMovement::RIGHT);
                break;
            case 'o':
                m_buffer_pane->enter_insert_mode(EnterInsertModeMode::NEW_LINE_AFTER);
                break;
            case 'r':
                m_buffer_pane->redo();
                break;
            case 'u':
                m_buffer_pane->undo();
                break;
            case 'x':
                m_buffer_pane->kill_character_at_cursor();
                break;
            case Keymod::CTRL + 'b':
                m_buffer_pane->scroll_window_up(ScrollMode::WHOLE_SCREEN);
                break;
            case Keymod::CTRL + 'd':
                m_buffer_pane->scroll_window_down(ScrollMode::HALF_SCREEN);
                break;
            case Keymod::CTRL + 'e':
                m_buffer_pane->scroll_window_down(ScrollMode::ONE_LINE);
                break;
            case Keymod::CTRL + 'f':
                m_buffer_pane->scroll_window_down(ScrollMode::WHOLE_SCREEN);
                break;
            case Keymod::CTRL + 'u':
                m_buffer_pane->scroll_window_up(ScrollMode::HALF_SCREEN);
                break;
            case Keymod::CTRL + 'w':
                m_buffer_pane->write_file();
                break;
            case Keymod::CTRL + 'y':
                m_buffer_pane->scroll_window_up(ScrollMode::ONE_LINE);
                break;
            case Keymod::CTRL + 'q':
                m_exit_requested = true;
                break;
            }
        }
        break;
    }
}

void Window::resize()
{
    SDL_GetWindowSize(m_window, &m_width, &m_height);
    glViewport(0, 0, m_width, m_height);
    m_gl->resize(m_width, m_height);
    m_buffer_pane->move(0, 0);
    m_buffer_pane->resize(m_width, m_height);
}

void Window::redraw()
{
    glClear(GL_COLOR_BUFFER_BIT);

    m_buffer_pane->draw();

    SDL_GL_SwapWindow(m_window);
}

uint32_t Window::get_keyval(SDL_Keycode keysym)
{
    uint32_t keyval = keysym;
    if ((m_keymod & (KMOD_SHIFT | KMOD_CAPS)) != 0u)
    {
        uint32_t shifted = get_shifted(keyval);
        if (shifted != keyval)
        {
            keyval = shifted;
        }
        else
        {
            keyval |= Keymod::SHIFT;
        }
    }
    if ((m_keymod & KMOD_CTRL) != 0u)
    {
        keyval |= Keymod::CTRL;
    }
    if ((m_keymod & KMOD_ALT) != 0u)
    {
        keyval |= Keymod::ALT;
    }
    if ((m_keymod & KMOD_GUI) != 0u)
    {
        keyval |= Keymod::GUI;
    }
    return keyval;
}

uint32_t Window::get_shifted(uint32_t keysym)
{
    if ((keysym >= 'a') && (keysym <= 'z'))
    {
        return keysym - ('a' - 'A');
    }

    switch (keysym)
    {
    case SDLK_QUOTE:        return '"';
    case SDLK_COMMA:        return '<';
    case SDLK_MINUS:        return '_';
    case SDLK_PERIOD:       return '>';
    case SDLK_SLASH:        return '?';
    case SDLK_0:            return ')';
    case SDLK_1:            return '!';
    case SDLK_2:            return '@';
    case SDLK_3:            return '#';
    case SDLK_4:            return '$';
    case SDLK_5:            return '%';
    case SDLK_6:            return '^';
    case SDLK_7:            return '&';
    case SDLK_8:            return '*';
    case SDLK_9:            return '(';
    case SDLK_SEMICOLON:    return ':';
    case SDLK_EQUALS:       return '+';
    case SDLK_LEFTBRACKET:  return '{';
    case SDLK_BACKSLASH:    return '|';
    case SDLK_RIGHTBRACKET: return '}';
    case SDLK_BACKQUOTE:    return '~';
    }

    return keysym;
}
