#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <sys\timeb.h>

#include "Timing.h"
#include "TapUi.h"
#include "TapLoader.h"
#include "Log.h"

#define _ADDR_BUTTON_AREA_LEFT 248
#define _BUTTON_SIDE_LENGTH 8
#define _TAP_UI_HEIGHT (_BUTTON_SIDE_LENGTH+1)    // at zoom 1
#define _BUTTON_SPACING_FACTOR (1.2f)

#define _TURBO_INITIAL_VALUE 1

SDL_Rect _tapui_window_rectangle;
TTF_Font* _tapui_font;
Uint8 _tapui_zoom;
Uint8 _tapui_initialized = 0;

Uint64 _tapui_frame_counter = 0;

#define _DEBUG_BUFFER_SIZE 256
static char _debugBuffer[_DEBUG_BUFFER_SIZE];

#define _MESSAGE_BUFFER_SIZE 256
static char _messageBuffer[_MESSAGE_BUFFER_SIZE];

// duration at the start before which we won't hide the UI
#define _TAPUI_HIDE_INITIAL_COOLDOWN_MS 3000

struct timeb _tapui_start_time;
static Uint8 _tapuiIsUIHidden = 0;

static Uint8 _tapui_autohide;

struct tapuiButton {
    SDL_Rect location;
    SDL_Texture* textureEnabled;
    SDL_Texture* textureDisabled;
    Uint8 isEnabled;
    SDL_RendererFlip flip;
    void (*onClick)();
};

#define _BUTTON_COUNT 6
struct tapuiButton* _tapui_button__play;
struct tapuiButton* _tapui_button__stop;
struct tapuiButton* _tapui_button__seek_previous;
struct tapuiButton* _tapui_button__seek_next;
struct tapuiButton* _tapui_button__turbo;
struct tapuiButton* _tapui_button__play_one;
struct tapuiButton _tapui_buttons[_BUTTON_COUNT];

void _tapui_renderButton(SDL_Renderer* renderer, struct tapuiButton* button) {
    SDL_Texture* texture = button->isEnabled ? button->textureEnabled : button->textureDisabled;
    SDL_RenderCopyEx(renderer, texture, NULL, &button->location, 0.0f, NULL, button->flip);
}

SDL_Texture* _tapui_loadImage(char* file, SDL_Renderer* renderer)
{
    SDL_Surface* loadedImage;
    SDL_Texture* texture;
    loadedImage = IMG_Load(file);

    if (loadedImage != NULL)
    {
        texture = SDL_CreateTextureFromSurface(renderer, loadedImage);
        if (texture == NULL) {
            sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE - 10, "Error: unable to create texture from file %s", file);
            log_write(_debugBuffer);
        }
        SDL_FreeSurface(loadedImage);
    }
    else {
        sprintf_s(_debugBuffer, _DEBUG_BUFFER_SIZE-10, "Error: unable to load surface from image file %s", file);
        log_write(_debugBuffer);
        return NULL;
    }

    return texture;
}

Uint16 tapui_get_UI_height(Uint8 zoom) {
	return _TAP_UI_HEIGHT * zoom;
}

void _tapui_handle_stop() {
    _tapui_button__stop->isEnabled = 0;
    _tapui_button__seek_next->isEnabled = 1;
    _tapui_button__seek_previous->isEnabled = 1;
    _tapui_button__play->isEnabled = 1;
    _tapui_button__play_one->isEnabled = 1;
}

void _tapui_on_stop_handler() {
    _tapui_handle_stop();
}

void _tapui_handle_play() {
    _tapui_button__stop->isEnabled = 1;
    _tapui_button__seek_next->isEnabled = 0;
    _tapui_button__seek_previous->isEnabled = 0;
    _tapui_button__play->isEnabled = 0;
    _tapui_button__play_one->isEnabled = 0;
}

void _tapui_on_play_handler() {
    _tapui_handle_play();
}

void _tapui_render_text(SDL_Renderer* renderer, char* text) {
    SDL_Color textColour = { 200, 200, 200 };
    SDL_Surface* messageSurface = TTF_RenderText_Solid(_tapui_font, text, textColour);
    SDL_Texture* messageTexture = SDL_CreateTextureFromSurface(renderer, messageSurface);

    SDL_FreeSurface(messageSurface);

    SDL_Rect textureRectangle;
    textureRectangle.x = _tapui_window_rectangle.x;
    textureRectangle.y = _tapui_window_rectangle.y;

    TTF_SizeText(_tapui_font, (const char*)text, &textureRectangle.w, &textureRectangle.h);

    SDL_RenderCopy(renderer, messageTexture, NULL, &textureRectangle);

    SDL_DestroyTexture(messageTexture);
}

void tapui_mouseclick() {
    if (!_tapui_initialized) {
        return;
    }

    SDL_Point mousePointer;
    SDL_GetMouseState(&mousePointer.x, &mousePointer.y);
    if (!SDL_PointInRect(&mousePointer, &_tapui_window_rectangle)) {
        // click was outside our UI
        return;
    }

    // check buttons for a click
    for (int i = 0; i < _BUTTON_COUNT; i++) {
        if (SDL_PointInRect(&mousePointer, &_tapui_buttons[i].location)) {
            _tapui_buttons[i].onClick();
        }
    }
}

void _tapui_render_file_not_loaded(SDL_Renderer* renderer) {
    _tapui_render_text(renderer, "Tape file not loaded");
}

// returns 0 when mouse pointer is outside our UI; other value otherwise
Uint8 _tapui_is_mouse_within_ui(SDL_Point* mouseLocation) {
    if (SDL_PointInRect(mouseLocation, &_tapui_window_rectangle)) {
        return 1;
    }

    return 0;
}

void _tapui_recompute_hidden_status() {
    struct timeb now;
    ftime(&now);
    Uint64 timeSinceStartMs = (Uint64)(1000.0 * (now.time - _tapui_start_time.time)
        + (now.millitm - _tapui_start_time.millitm));

    if (timeSinceStartMs <= _TAPUI_HIDE_INITIAL_COOLDOWN_MS) {
        return;
    }

    SDL_Point mousePointer;
    SDL_GetMouseState(&mousePointer.x, &mousePointer.y);

    _tapuiIsUIHidden = 1;
    if (_tapui_is_mouse_within_ui(&mousePointer)) {
        _tapuiIsUIHidden = 0;
    }
}

Uint8 tapui_render(SDL_Renderer* renderer) {
    if (!_tapui_initialized) {
        return 0;
    }

    _tapui_frame_counter++;

    _tapui_recompute_hidden_status();
    if (_tapui_autohide &&_tapuiIsUIHidden) {
        // we rendered nothing
        return 0;
    }

    // erase everything
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderFillRect(renderer, &_tapui_window_rectangle);

    if (!taploader_is_file_loaded()) {
        // shortcircuit when tape file is not loaded at all
        _tapui_render_file_not_loaded(renderer);
        return 0;
    }

    // render progress indicator through current TAP block as a solid background colour
    struct tapRunState tapeState = taploader_get_state();
    if (tapeState.type == DataBytes) {
        Uint64 currentDataByteOffset = tapeState.dataBytePointer - tapeState.block->tapBlockBytes;
        Uint64 currentBlockSize = tapeState.block->blockDataSize;
        double percent = (double)currentDataByteOffset / (double)currentBlockSize;
        if (percent > 1.0f) {
            percent = 1.0f;
        }

        // draw the progress bar
        Uint8 red = 75, green = 0, blue = 150;
        SDL_SetRenderDrawColor(renderer, red, green, blue, 255);
        SDL_Rect progressRect = _tapui_window_rectangle;
        progressRect.w = (int)((double)_tapui_window_rectangle.w * percent);
        SDL_RenderFillRect(renderer, &progressRect);

        // draw the leader (that is, the more visible thin line at the head of the progress bar)
        int leaderWidth = _tapui_zoom * 1;
        Uint8 leaderRed = 225, leaderGreen = 128, leaderBlue = 255;
        SDL_SetRenderDrawColor(renderer, leaderRed, leaderGreen, leaderBlue, 255);
        SDL_Rect progressHeadRect = progressRect;
        progressHeadRect.x = progressHeadRect.w + progressHeadRect.x - leaderWidth;
        progressHeadRect.w = leaderWidth;
        SDL_RenderFillRect(renderer, &progressHeadRect);
        // .. and has a tail
        /*SDL_SetRenderDrawColor(renderer, red + 100, 0, blue + 100, 255);
        progressHeadRect.x -= leaderWidth;
        SDL_RenderFillRect(renderer, &progressHeadRect);*/
        // .. more tail
        /*SDL_SetRenderDrawColor(renderer, red + 50, 0, blue + 50, 255);
        progressHeadRect.x -= leaderWidth;
        SDL_RenderFillRect(renderer, &progressHeadRect);*/
    }

    // render buttons
    for (int i = 0; i < _BUTTON_COUNT; i++) {
        _tapui_renderButton(renderer, &_tapui_buttons[i]);
    }

    // render text
    Uint16 lastBlockIndex = taploader_get_block_count()-1;
    if (tapeState.block->type == Header) {
        sprintf_s(_messageBuffer, _MESSAGE_BUFFER_SIZE - 10, "%03d/%03d %s %s %ub",
            tapeState.block->blockIndex,
            lastBlockIndex,
            tapeState.block->flagByteHumanReadable,
            tapeState.block->headerInfo->filename,
            tapeState.block->blockRawDataSize);
    }
    else {
        // don't display filename for non-header blocks
        sprintf_s(_messageBuffer, _MESSAGE_BUFFER_SIZE - 10, "%03d/%03d %s            %ub",
            tapeState.block->blockIndex,
            lastBlockIndex,
            tapeState.block->flagByteHumanReadable,
            tapeState.block->blockRawDataSize);
    }
    
    _tapui_render_text(renderer, _messageBuffer);
    return 1;
}

void _tapui__onclick_turbo() {
    _tapui_button__turbo->isEnabled ^= 1;
    taploader_set_desired_turbo(_tapui_button__turbo->isEnabled);
}

void _tapui__onclick_seek_previous() {
    if (!_tapui_button__seek_previous->isEnabled) {
        return;
    }

    if (taploader_get_state().type != Stopped) {
        return;
    }

    _tapui_button__stop->isEnabled = 0;
    _tapui_button__seek_next->isEnabled = 1;
    _tapui_button__seek_previous->isEnabled = 1;
    _tapui_button__play->isEnabled = 1;
    taploader_seek_previous();
}

void _tapui__onclick_seek_next() {
    if (!_tapui_button__seek_next->isEnabled) {
        return;
    }

    if (taploader_get_state().type != Stopped) {
        return;
    }

    _tapui_button__stop->isEnabled = 0;
    _tapui_button__seek_next->isEnabled = 1;
    _tapui_button__seek_previous->isEnabled = 1;
    _tapui_button__play->isEnabled = 1;
    taploader_seek_next();
}

void _tapui__onclick_play() {
    if (!_tapui_button__play->isEnabled) {
        return;
    }

    if (taploader_get_state().type != Stopped) {
        return;
    }

    taploader_press_play(1);
    // button state will be taken care of by the "play handler", invoked by the taploader
}

void _tapui__onclick_play_one() {
    if (!_tapui_button__play_one->isEnabled) {
        return;
    }

    if (taploader_get_state().type != Stopped) {
        return;
    }

    taploader_press_play(0);
    // button state will be taken care of by the "play handler", invoked by the taploader
}

void _tapui__onclick_stop() {
    if (!_tapui_button__stop->isEnabled) {
        return;
    }
    taploader_press_stop();
    // button state will be taken care of by the "stop handler", invoked by the taploader
}

void _tapui_create_buttons(SDL_Renderer* renderer) {
    SDL_Rect location = _tapui_window_rectangle;
    location.x = _tapui_window_rectangle.x + _ADDR_BUTTON_AREA_LEFT * _tapui_zoom;
    location.y = _tapui_window_rectangle.y;
    location.w = _BUTTON_SIDE_LENGTH * _tapui_zoom;
    location.h = _BUTTON_SIDE_LENGTH * _tapui_zoom;

    struct tapuiButton turbo;
    turbo.flip = SDL_FLIP_NONE;
    turbo.isEnabled = _TURBO_INITIAL_VALUE;
    turbo.location = location;
    turbo.onClick = _tapui__onclick_turbo;
    turbo.textureDisabled = _tapui_loadImage("data\\turbo_off.png", renderer);
    turbo.textureEnabled = _tapui_loadImage("data\\turbo_on.png", renderer);
    _tapui_buttons[0] = turbo;
    _tapui_button__turbo = &_tapui_buttons[0];

    location.x += (int)(_BUTTON_SPACING_FACTOR * _BUTTON_SIDE_LENGTH * _tapui_zoom);
    struct tapuiButton seek_previous;
    seek_previous.flip = SDL_FLIP_HORIZONTAL;
    seek_previous.isEnabled = 1;
    seek_previous.location = location;
    seek_previous.onClick = _tapui__onclick_seek_previous;
    seek_previous.textureDisabled = _tapui_loadImage("data\\seek_next_disabled.png", renderer);
    seek_previous.textureEnabled = _tapui_loadImage("data\\seek_next.png", renderer);
    _tapui_buttons[1] = seek_previous;
    _tapui_button__seek_previous = &_tapui_buttons[1];

    location.x += (int)(_BUTTON_SPACING_FACTOR * _BUTTON_SIDE_LENGTH * _tapui_zoom);
    struct tapuiButton play;
    play.flip = SDL_FLIP_NONE;
    play.isEnabled = 1;
    play.location = location;
    play.onClick = _tapui__onclick_play;
    play.textureDisabled = _tapui_loadImage("data\\play_disabled.png", renderer);
    play.textureEnabled = _tapui_loadImage("data\\play.png", renderer);
    _tapui_buttons[2] = play;
    _tapui_button__play = &_tapui_buttons[2];

    location.x += (int)(_BUTTON_SPACING_FACTOR * _BUTTON_SIDE_LENGTH * _tapui_zoom);
    struct tapuiButton playOne;
    playOne.flip = SDL_FLIP_NONE;
    playOne.isEnabled = 1;
    playOne.location = location;
    playOne.onClick = _tapui__onclick_play_one;
    playOne.textureDisabled = _tapui_loadImage("data\\play_one_disabled.png", renderer);
    playOne.textureEnabled = _tapui_loadImage("data\\play_one.png", renderer);
    _tapui_buttons[3] = playOne;
    _tapui_button__play_one = &_tapui_buttons[3];

    location.x += (int)(_BUTTON_SPACING_FACTOR * _BUTTON_SIDE_LENGTH * _tapui_zoom);
    struct tapuiButton stop;
    stop.flip = SDL_FLIP_NONE;
    stop.isEnabled = 0;
    stop.location = location;
    stop.onClick = _tapui__onclick_stop;
    stop.textureDisabled = _tapui_loadImage("data\\stop_disabled.png", renderer);
    stop.textureEnabled = _tapui_loadImage("data\\stop.png", renderer);
    _tapui_buttons[4] = stop;
    _tapui_button__stop = &_tapui_buttons[4];

    location.x += (int)(_BUTTON_SPACING_FACTOR * _BUTTON_SIDE_LENGTH * _tapui_zoom);
    struct tapuiButton seek_next;
    seek_next.flip = SDL_FLIP_NONE;
    seek_next.isEnabled = 1;
    seek_next.location = location;
    seek_next.onClick = _tapui__onclick_seek_next;
    seek_next.textureDisabled = _tapui_loadImage("data\\seek_next_disabled.png", renderer);
    seek_next.textureEnabled = _tapui_loadImage("data\\seek_next.png", renderer);
    _tapui_buttons[5] = seek_next;
    _tapui_button__seek_next = &_tapui_buttons[5];
}

void tapui_click_turbo() {
    _tapui__onclick_turbo();
}

void tapui_start(SDL_Window* window, SDL_Renderer* renderer, Uint16 width, Uint16 height, Uint16 top, Uint16 left, Uint8 zoom, Uint8 autohide) {
    _tapui_zoom = zoom;
    _tapui_window_rectangle.x = left;
    _tapui_window_rectangle.y = top;
    _tapui_window_rectangle.w = width;
    _tapui_window_rectangle.h = height;
    _tapuiIsUIHidden = 0;
    _tapui_autohide = autohide;

    if (TTF_Init() < 0) {
        log_write("Error: could not initialize fonts");
        return;
    }

    _tapui_font = TTF_OpenFont("data\\zx-spectrum.ttf", 7 * _tapui_zoom);   // this gives the same size as the ZX's font
    if (_tapui_font == NULL) {
        log_write("Error: unable to open font file");
        return;
    }

    ftime(&_tapui_start_time);

    _tapui_create_buttons(renderer);
    taploader_set_desired_turbo(_TURBO_INITIAL_VALUE);
    taploader_set_on_stop_handler(_tapui_on_stop_handler);
    taploader_set_on_play_handler(_tapui_on_play_handler);

    _tapui_initialized = 1;
}

void tapui_destroy() {
    if (!_tapui_initialized) {
        return;
    }

    for (int i = 0; i < _BUTTON_COUNT; i++) {
        SDL_DestroyTexture(_tapui_buttons[i].textureDisabled);
        SDL_DestroyTexture(_tapui_buttons[i].textureEnabled);
    }

    TTF_CloseFont(_tapui_font);
}
