#include "gl3w.h"
#include "Window.h"
#include "Runtime.h"
#include "BufferPane.h"
#include <iostream>
#include "jes_icon-32x32.h"
#include <unistd.h>
#include <unordered_map>
#include "DefaultCommandMap.h"

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

/* Process multiple queued events for up to this long before stopping to
 * redraw the screen. */
#define MAX_EVENT_PROCESS_TIME 50000

/**
 * Initialize OpenGL.
 *
 * @retval true OpenGL was loaded successfully.
 * @retval false Loading OpenGL failed.
 */
static bool Initialize_OpenGL()
{
    if (gl3wInit() != 0)
    {
        std::cerr << "Failed to initialize gl3w." << std::endl;

        /* Failed to gl3wInit() */
        return false;
    }

    if (!gl3wIsSupported(3, 0))
    {
        std::cerr << "Error: OpenGL 3.0 is required." << std::endl;

        std::cerr << "OpenGL version: "
            << glGetString(GL_VERSION)
            << ", GLSL: "
            << glGetString(GL_SHADING_LANGUAGE_VERSION)
            << std::endl;

        /* 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;
}

void Window::set_window_icon()
{
    uint8_t * icon_bgra = (uint8_t *)malloc(32u * 32u * 4u);
    uint8_t * out_icon = icon_bgra;
    const uint8_t * in_icon = jes_icon_32x32;
    for (int row = 0; row < 32; row++)
    {
        for (int col = 0; col < 32; col++)
        {
            uint8_t r = *in_icon++;
            uint8_t g = *in_icon++;
            uint8_t b = *in_icon++;
            *out_icon++ = b;
            *out_icon++ = g;
            *out_icon++ = r;
            *out_icon++ = 0xFFu;
        }
    }
    Jtk_SetWindowIcon(m_window, icon_bgra, 32, 32);
    free(icon_bgra);
}

/**
 * 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 (!Jtk_Init())
    {
        std::cerr << "Error initializing GUI" << std::endl;
        return false;
    }

    m_window = Jtk_CreateWindow();
    if (m_window == NULL)
    {
        std::cerr << "Error creating window" << std::endl;
        return false;
    }
    Jtk_SetWindowTitle(m_window, "jes");

    set_window_icon();

    if (!Initialize_OpenGL())
    {
        std::cerr << "Error initializing OpenGL" << std::endl;
        return false;
    }

    m_exit_requested = false;

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

    m_font = std::make_shared<Font>();
    if (!m_font->load(font_path.c_str(), FONT_SIZE))
    {
        std::cerr << "Error loading font" << std::endl;
        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);
    m_focused_buffer_pane = m_buffer_pane;
    m_buffer_pane->set_focused(true);
    m_command_buffer = std::make_shared<Buffer>();
    m_command_buffer_pane = std::make_shared<BufferPane>(this, m_command_buffer);
    m_command_buffer_pane->set_command_mode();
    m_command_buffer_screen_rows = 1;
    m_command_invalid = false;

    resize(INITIAL_WIDTH, INITIAL_HEIGHT);

    m_redraw_requested = true;

    return true;
}

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

    while (!m_exit_requested)
    {
        if (m_redraw_requested)
        {
            m_redraw_requested = false;
            redraw();
        }
        Jtk_WaitEvent(&event);
        uint64_t event_time = Jtk_UsTime();
        handle_event(event);
        while (Jtk_CheckEvent(&event) &&
                ((Jtk_UsTime() - event_time) < MAX_EVENT_PROCESS_TIME))
        {
            handle_event(event);
        }
    }
}

/**
 * Handle a Jtk event.
 */
void Window::handle_event(Jtk_Event & event)
{
    switch (event.type)
    {
    case JTK_EVENT_WINDOW_CLOSE:
        m_exit_requested = true;
        break;

    case JTK_EVENT_KEY_PRESS:
#if 0
        if (!event.key.repeat)
        {
            Jtk_BeginKeyRepeat(&event.key, 300u, 25u);
        }
#endif
        handle_keypress(event.key.key);
        m_redraw_requested = true;
        break;

    case JTK_EVENT_WINDOW_EXPOSE:
        m_redraw_requested = true;
        break;

    case JTK_EVENT_WINDOW_RESIZE:
        resize(event.resize.width, event.resize.height);
        m_redraw_requested = true;
        break;

    case JTK_EVENT_BUTTON_PRESS:
        if (event.button.button == 4)
        {
            m_focused_buffer_pane->scroll_window_up(ScrollMode::WHEEL);
        }
        else if (event.button.button == 5)
        {
            m_focused_buffer_pane->scroll_window_down(ScrollMode::WHEEL);
        }
        break;
    }
}

void Window::handle_keypress(uint32_t keyval)
{
    uint32_t ctrl_keyval = keyval & (JES_KEY_KEYCODE_MASK | JES_KEY_MODS_CTRL);
    uint32_t keycode = keyval & JES_KEY_KEYCODE_MASK;
    if ((JES_KEY_SHIFT_L <= keycode) && (keycode <= JES_KEY_SUPER_R))
    {
        /* Ignore modifier key presses. */
    }
    else if (m_focused_buffer_pane->insert_mode())
    {
        if (keycode == '\033')
        {
            if (m_focused_buffer_pane == m_command_buffer_pane)
            {
                m_command_buffer_pane->clear();
                m_command_buffer_screen_rows = 1;
                change_focus(m_buffer_pane);
            }
            else
            {
                m_focused_buffer_pane->exit_insert_mode();
            }
        }
        else if ((keycode == '\n') && (m_focused_buffer_pane == m_command_buffer_pane))
        {
            EncodedString command = m_command_buffer->get_string();
            m_command_buffer_pane->clear();
            m_command_buffer_screen_rows = 1;
            change_focus(m_buffer_pane);
            handle_command(command);
        }
        else if (ctrl_keyval <= 0xFFu)
        {
            m_focused_buffer_pane->insert_code_point(ctrl_keyval);
        }
        else
        {
            switch (ctrl_keyval)
            {
            case JES_KEY_HOME:
                m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::SOL, 0u);
                break;
            case JES_KEY_END:
                m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::EOL, 0u);
                break;
            case JES_KEY_RIGHT:
                m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::RIGHT, 0u);
                break;
            case JES_KEY_LEFT:
                m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::LEFT, 0u);
                break;
            case JES_KEY_DOWN:
                m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::DOWN, 0u);
                break;
            case JES_KEY_UP:
                m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::UP, 0u);
                break;
            case JES_KEY_PAGE_UP:
                m_focused_buffer_pane->scroll_window_up(ScrollMode::WHOLE_SCREEN);
                break;
            case JES_KEY_PAGE_DOWN:
                m_focused_buffer_pane->scroll_window_down(ScrollMode::WHOLE_SCREEN);
                break;
            }
        }
    }
    else
    {
        if ((keycode == '\033') || (keycode == '\b'))
        {
            m_command_input.clear();
            m_command_invalid = false;
        }
        else if (keycode == ':')
        {
            m_command_buffer_pane->clear();
            change_focus(m_command_buffer_pane);
        }
        else
        {
            m_command_input.push_back(ctrl_keyval);
            evaluate_command_input();
        }
    }
}

void Window::evaluate_command_input()
{
    auto cm = DefaultCommandMap::get();
    Command command;
    switch (cm->lookup_command(&m_command_input[0], m_command_input.size(), command))
    {
    case CommandMap::COMMAND_INVALID:
        m_command_invalid = true;
        break;
    case CommandMap::COMMAND_INCOMPLETE:
        break;
    case CommandMap::COMMAND_COMPLETE:
        execute_command(command);
        m_command_input.clear();
        break;
    }
}

void Window::execute_command(const Command & command)
{
    switch (command.main.id)
    {
    case Command::GO_FORWARD_UP_TO_CHAR:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::FORWARD_UP_TO_CHAR, command.main.following_char);
        break;
    case Command::GO_FORWARD_ON_TO_CHAR:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::FORWARD_ON_TO_CHAR, command.main.following_char);
        break;
    case Command::GO_BACK_UP_TO_CHAR:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::BACK_UP_TO_CHAR, command.main.following_char);
        break;
    case Command::GO_BACK_ON_TO_CHAR:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::BACK_ON_TO_CHAR, command.main.following_char);
        break;
    case Command::DELETE_MOTION:
        break;
    case Command::DELETE_LINE:
        break;
    case Command::DELETE_CHAR:
        m_focused_buffer_pane->kill_character_forward();
        break;
    case Command::DELETE_CHAR_BACK:
        m_focused_buffer_pane->kill_character_backward();
        break;
    case Command::CHANGE_MOTION:
        break;
    case Command::CHANGE_LINE:
        break;
    case Command::YANK_MOTION:
        break;
    case Command::YANK_LINE:
        break;
    case Command::UNDO:
        m_focused_buffer_pane->undo();
        break;
    case Command::REDO:
        m_focused_buffer_pane->redo();
        break;
    case Command::ENTER_INSERT_MODE:
        m_focused_buffer_pane->enter_insert_mode(EnterInsertModeMode::START_OF_CHAR);
        break;
    case Command::ENTER_INSERT_MODE_AFTER_CHAR:
        m_focused_buffer_pane->enter_insert_mode(EnterInsertModeMode::END_OF_CHAR);
        break;
    case Command::ENTER_INSERT_MODE_AFTER_LINE:
        m_focused_buffer_pane->enter_insert_mode(EnterInsertModeMode::END_OF_LINE);
        break;
    case Command::ENTER_INSERT_MODE_START_OF_LINE:
        m_focused_buffer_pane->enter_insert_mode(EnterInsertModeMode::START_OF_LINE);
        break;
    case Command::ENTER_INSERT_MODE_NEW_LINE_BEFORE:
        m_focused_buffer_pane->enter_insert_mode(EnterInsertModeMode::NEW_LINE_BEFORE);
        break;
    case Command::ENTER_INSERT_MODE_NEW_LINE_AFTER:
        m_focused_buffer_pane->enter_insert_mode(EnterInsertModeMode::NEW_LINE_AFTER);
        break;
    case Command::PUT:
        break;
    case Command::PUT_BEFORE:
        break;
    case Command::CHANGE_CHAR:
        break;
    case Command::GO_TO_LINE:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::FIRST_LINE, 0u);
        break;
    case Command::GO_TO_LAST_LINE:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::LAST_LINE, 0u);
        break;
    case Command::GO_LEFT:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::LEFT, 0u);
        break;
    case Command::GO_DOWN:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::DOWN, 0u);
        break;
    case Command::GO_UP:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::UP, 0u);
        break;
    case Command::GO_RIGHT:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::RIGHT, 0u);
        break;
    case Command::GO_START_OF_LINE:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::SOL, 0u);
        break;
    case Command::GO_END_OF_LINE:
        m_focused_buffer_pane->cursor_move(BufferPane::CursorMovement::EOL, 0u);
        break;
    case Command::NEXT:
        break;
    case Command::PREV:
        break;
    case Command::SCROLL_WINDOW_UP_ONE_LINE:
        m_focused_buffer_pane->scroll_window_up(ScrollMode::ONE_LINE);
        break;
    case Command::SCROLL_WINDOW_DOWN_ONE_LINE:
        m_focused_buffer_pane->scroll_window_down(ScrollMode::ONE_LINE);
        break;
    case Command::SCROLL_WINDOW_UP_HALF_SCREEN:
        m_focused_buffer_pane->scroll_window_up(ScrollMode::HALF_SCREEN);
        break;
    case Command::SCROLL_WINDOW_DOWN_HALF_SCREEN:
        m_focused_buffer_pane->scroll_window_down(ScrollMode::HALF_SCREEN);
        break;
    case Command::SCROLL_WINDOW_UP_WHOLE_SCREEN:
        m_focused_buffer_pane->scroll_window_up(ScrollMode::WHOLE_SCREEN);
        break;
    case Command::SCROLL_WINDOW_DOWN_WHOLE_SCREEN:
        m_focused_buffer_pane->scroll_window_down(ScrollMode::WHOLE_SCREEN);
        break;
    }
}

void Window::resize(size_t width, size_t height)
{
    m_width = width;
    m_height = height;
    glViewport(0, 0, m_width, m_height);
    m_gl->resize(m_width, m_height);
    int command_buffer_height = m_command_buffer_screen_rows * m_font->get_line_height();
    m_buffer_pane->move(0, command_buffer_height + 1);
    m_buffer_pane->resize(m_width, m_height - command_buffer_height - 1);
    m_command_buffer_pane->resize(m_width, command_buffer_height);
    m_command_buffer_pane->move(0, 0);
}

void Window::redraw()
{
    static int last_command_buffer_screen_rows = 0;
    /* TODO: figure out number of command buffer screen rows. */
    m_command_buffer_screen_rows = 1;
    if (m_command_buffer_screen_rows != last_command_buffer_screen_rows)
    {
        resize(m_width, m_height);
    }
    last_command_buffer_screen_rows = m_command_buffer_screen_rows;

    glClear(GL_COLOR_BUFFER_BIT);

    m_buffer_pane->draw();
    m_gl->draw_rect(0, m_command_buffer_screen_rows * m_font->get_line_height(), m_width, 1, 0.5, 0.5, 0.5, 1.0);
    if (m_focused_buffer_pane->insert_mode())
    {
        m_command_buffer_pane->draw();
    }
    else
    {
        draw_command_input();
    }

    Jtk_SwapBuffers(m_window);
}

void Window::draw_command_input()
{
    int x = 0;
    float g, b;
    if (m_command_invalid)
    {
        g = 0.0;
        b = 0.0;
    }
    else
    {
        g = 1.0;
        b = 1.0;
    }
    for (size_t i = 0u, length = m_command_input.size(); i < length; i++)
    {
        m_gl->draw_character(x, 0, m_command_input[i], *m_font, 1.0, g, b, 1.0);
        x += m_font->get_advance();
    }
}

void Window::change_focus(std::shared_ptr<BufferPane> buffer_pane)
{
    m_focused_buffer_pane->set_focused(false);
    m_focused_buffer_pane = buffer_pane;
    m_focused_buffer_pane->set_focused(true);
    request_redraw();
}

void Window::handle_command(const EncodedString & command)
{
    CommandParser cp;
    if (cp.parse(command))
    {
        if (cp.size() >= 1)
        {
            if (cp[0] == "w")
            {
                command_write_file(cp);
            }
            else if (cp[0] == "q")
            {
                command_quit(cp);
            }
        }
    }
    else
    {
        /* TODO: handle command parsing failure */
    }
}

void Window::command_write_file(const CommandParser & cp)
{
    std::shared_ptr<Buffer> buffer = m_focused_buffer_pane->buffer();
    if (buffer->filename())
    {
        buffer->write_to_file(buffer->filename()->c_str());
    }
}

void Window::command_quit(const CommandParser & cp)
{
    m_exit_requested = true;
}
