/*
 * Voxel-a-tord
 * display.c:
 * Copyright (c) 2021-2022 986-Studio. All rights reserved.
 *
 * Created by Manoël Trapier on 01/03/2021.
 */

#include <stdio.h>
#include <stdbool.h>

#include <SDL.h>
#include <SDL_ttf.h>

#include <log.h>
#include <display.h>
#include <colour.h>

/***********************************************************************************************************************
 * Variables
 **********************************************************************************************************************/
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
static colour_t *frameBuffer = NULL;
static double *zBuffer = NULL;
static SDL_Texture *frameBufferTexture = NULL;
static int32_t windowWidth = 1024;
static int32_t windowHeight = 768;
static TTF_Font *font = NULL;

/***********************************************************************************************************************
 * Functions
 **********************************************************************************************************************/
#define MAX(_a, _b) ((_a) < (_b)) ? (_b) : (_a)
#define MIN(_a, _b) ((_a) > (_b)) ? (_b) : (_a)

static inline void intSwap(int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}


bool initialiseWindow(int32_t width, int32_t height, bool fullScreen)
{
    bool ret = false;
    int windowFlags = 0;
    int fullscreenWidth;
    int fullscreenHeight;

    if (SDL_Init(SDL_INIT_EVERYTHING))
    {
        Log(TLOG_PANIC, NULL, "SDL Initialisation error!! error: %s", SDL_GetError());
        goto exit;
    }

    Log(TLOG_DEBUG, NULL, "SDL properly initialised!");

    ret = TTF_Init();
    if (ret)
    {
        Log(TLOG_PANIC, NULL, "SDL_ttf Initialisation error!! error: %s", SDL_GetError());
        goto exit;
    }

    windowWidth = width;
    windowHeight = height;

    if (fullScreen)
    {
        Log(TLOG_DEBUG, NULL, "Will go fullscreen! Fasten your seatbelts!");
        SDL_DisplayMode displayMode;
        SDL_GetCurrentDisplayMode(0, &displayMode);

        fullscreenWidth = displayMode.w;
        fullscreenHeight = displayMode.h;

        windowFlags = SDL_WINDOW_BORDERLESS;
    }
    else
    {
        fullscreenWidth = width;
        fullscreenHeight = height;
    }

    window = SDL_CreateWindow(NULL, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, fullscreenWidth, fullscreenHeight,
                              windowFlags);
    if (window == NULL)
    {
        Log(TLOG_PANIC, NULL, "SDL Window creation error: %s", SDL_GetError());
        goto exit;
    }
    Log(TLOG_DEBUG, NULL, "SDL Window created!");

    renderer = SDL_CreateRenderer(window, -1, 0);
    if (renderer == NULL)
    {
        Log(TLOG_PANIC, NULL, "SDL Renderer creation error: %s", SDL_GetError());
        goto exit;
    }
    Log(TLOG_DEBUG, NULL, "SDL Renderer created!");

    font = TTF_OpenFont("assets/pico8.ttf", 8);
    if (font == NULL)
    {
        Log(TLOG_WARNING, NULL, "Cannot open the font for printing...: %s", SDL_GetError());
        goto exit;
    }

    frameBuffer = (uint32_t *)calloc(windowWidth * windowHeight, sizeof(uint32_t));
    if (!frameBuffer)
    {
        Log(TLOG_PANIC, NULL, "Memory allocation error.");
        goto exit;
    }

    zBuffer = (double *)calloc(windowWidth * windowHeight, sizeof(double));
    if (!frameBuffer)
    {
        Log(TLOG_PANIC, NULL, "Memory allocation error.");
        goto exit;
    }

    frameBufferTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, windowWidth,
                                           windowHeight);
    if (frameBufferTexture == NULL)
    {
        Log(TLOG_PANIC, NULL, "SDL Texture creation error: %s", SDL_GetError());
        goto exit;
    }

    if (fullScreen)
    {
        SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
    }

    ret = true;

exit:
    return ret;
}

void getWindowSize(int32_t *width, int32_t *height)
{
    *width = windowWidth;
    *height = windowHeight;
}

void destroyWindow()
{
    if (font != NULL)
    {
        TTF_CloseFont(font);
    }
    if (frameBuffer != NULL)
    {
        free(frameBuffer);
    }
    if (zBuffer != NULL)
    {
        free(zBuffer);
    }
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

void displayWindowClear()
{
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
}

void displayWindowRender()
{
    SDL_RenderPresent(renderer);
}

void renderFrameBuffer()
{
    SDL_UpdateTexture(frameBufferTexture, NULL, frameBuffer, (uint32_t)(windowWidth * sizeof(uint32_t)));
    SDL_RenderCopy(renderer, frameBufferTexture, NULL, NULL);
}

void drawText(int32_t x, int32_t y, colour_t colour, const char *format, ...)
{
    va_list va;
    uint8_t r = ((colour >> 16) & 0xFF);
    uint8_t g = ((colour >>  8) & 0xFF);
    uint8_t b = ((colour      ) & 0xFF);
    SDL_Color c = { r, g, b , 255};
    char buffer[512];

    va_start(va, format);
    vsnprintf(buffer, 512, format, va);
    va_end(va);

    SDL_Surface *surface = TTF_RenderText_Blended(font, buffer, c);
    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);

    int labelWidth, labelHeight;

    SDL_QueryTexture(texture, NULL, NULL, &labelWidth, &labelHeight);

    SDL_Rect destRect =
    {
        x, y, labelWidth, labelHeight
    };
    SDL_RenderCopyEx(renderer, texture, NULL, &destRect,0, NULL, SDL_FLIP_NONE);

    SDL_FreeSurface(surface);
    SDL_DestroyTexture(texture);
}

void drawPixel(int32_t x, int32_t y, colour_t colour)
{
    if ((x >= 0) && (x < windowWidth) && (y >= 0) && (y < windowHeight))
    {
        frameBuffer[x + (y * windowWidth)] = colour;
    }
}

void drawVLine(int32_t x, int32_t y0, int32_t y1, colour_t colour)
{
    int32_t i;
    if (y0 > y1) {
        intSwap(&y0, &y1); }

    if ( ((x < 0) || (x > windowWidth)) ||
         ((y0 < 0) && (y1 < 0)) ||
         ((y0 > windowHeight) && (y1 > windowHeight)) )
    {
        return;
    }

    y0 = MAX(0, y0);
    y1 = MIN(y1, (windowHeight - 1));

    uint32_t *currentPos = &frameBuffer[x + (y0 * windowWidth)];

    for(i = y0; i <= y1; i++, currentPos+=windowWidth)
    {
        *currentPos = colour;
    }
}

void drawHLine(int32_t x0, int32_t y, int32_t x1, colour_t colour)
{
    int32_t i;
    if (x0 > x1) {
        intSwap(&x0, &x1); }

    if ( ((y < 0) || (y > windowHeight)) ||
         ((x0 < 0) && (x1 < 0)) ||
         ((x0 > windowWidth) && (x1 > windowWidth)) )
    {
        return;
    }

    x0 = MAX(0, x0);
    x1 = MIN(x1, (windowWidth - 1));

    uint32_t *currentPos = &frameBuffer[x0 + (y * windowWidth)];

    for(i = x0; i <= x1; i++, currentPos++)
    {
        *currentPos = colour;
    }
}

void clearFrameBuffer(colour_t colour)
{
    int32_t x;
    for (x = 0 ; x < windowWidth * windowHeight ; x++)
    {
        frameBuffer[x] = colour;
    }
}

void drawGrid(int spacing, colour_t colour)
{
    int32_t x, y;
    for (y = 0 ; y < windowHeight ; y++)
    {
        for (x = 0 ; x < windowWidth ; x++)
        {
            if (((x % spacing) == 0) || ((y % spacing) == 0))
            {
                frameBuffer[x + (y * windowWidth)] = colour;
            }
        }
    }
}

void drawRectangle(int32_t x, int32_t y, int32_t w, int32_t h, colour_t colour)
{
    int32_t j;

    for (j = 0 ; j < h ; j++)
    {
        drawHLine(x, y + j, x + w, colour);
    }
}

/* FIXME: Some out of screen line may render weirdly. Will fix that later */
void drawLine(int32_t x0, int32_t y0, int32_t x1, int32_t y1, colour_t colour)
{
    int i;
    int32_t deltaX = x1 - x0;
    int32_t deltaY = y1 - y0;

    int32_t sideLength = ( abs(deltaX) >= abs(deltaY) ) ? abs(deltaX) : abs(deltaY);

    double incrementX = deltaX / (double)sideLength;
    double incrementY = deltaY / (double)sideLength;

    if (deltaX == 0)
    {
        drawVLine(x0, y0, y1, colour);
    }
    else if (deltaY == 0)
    {
        drawHLine(x0, y0, x1, colour);
    }
    else
    {
        double currentX = x0;
        double currentY = y0;

        for (i = 0 ; i < sideLength ; i++)
        {
            drawPixel(round(currentX), round(currentY), colour);
            currentX += incrementX;
            currentY += incrementY;
        }
    }
}
