#include "core/rendering/fade.h"

#include <SDL3/SDL.h>

#include <cstdlib>   // for rand
#include <iostream>  // for char_traits, basic_ostream, operator<<

#include "game/defaults.hpp"  // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH

// Constructor
Fade::Fade(SDL_Renderer *renderer)
    : renderer_(renderer) {
    backbuffer_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
    if (backbuffer_ != nullptr) {
        SDL_SetTextureScaleMode(backbuffer_, SDL_SCALEMODE_NEAREST);
    }
    if (backbuffer_ == nullptr) {
        std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << '\n';
    }
}

// Destructor
Fade::~Fade() {
    SDL_DestroyTexture(backbuffer_);
    backbuffer_ = nullptr;
}

// Inicializa las variables
void Fade::init(Uint8 r, Uint8 g, Uint8 b) {
    fade_type_ = FADE_CENTER;
    enabled_ = false;
    finished_ = false;
    counter_ = 0;
    r_ = r;
    g_ = g;
    b_ = b;
    r_original_ = r;
    g_original_ = g;
    b_original_ = b;
    last_square_ticks_ = 0;
    squares_drawn_ = 0;
    fullscreen_done_ = false;
}

// Pinta una transición en pantalla
void Fade::render() {
    if (enabled_ && !finished_) {
        switch (fade_type_) {
            case FADE_FULLSCREEN: {
                if (!fullscreen_done_) {
                    SDL_FRect fRect1 = {0, 0, (float)GAMECANVAS_WIDTH, (float)GAMECANVAS_HEIGHT};

                    int alpha = counter_ * 4;
                    if (alpha >= 255) {
                        fullscreen_done_ = true;

                        // Deja todos los buffers del mismo color
                        SDL_SetRenderTarget(renderer_, backbuffer_);
                        SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 255);
                        SDL_RenderClear(renderer_);

                        SDL_SetRenderTarget(renderer_, nullptr);
                        SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 255);
                        SDL_RenderClear(renderer_);

                        finished_ = true;
                    } else {
                        // Dibujamos sobre el renderizador
                        SDL_SetRenderTarget(renderer_, nullptr);

                        // Copia el backbuffer con la imagen que había al renderizador
                        SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);

                        SDL_SetRenderDrawColor(renderer_, r_, g_, b_, alpha);
                        SDL_RenderFillRect(renderer_, &fRect1);
                    }
                }
                break;
            }

            case FADE_CENTER: {
                SDL_FRect fR1 = {0, 0, (float)GAMECANVAS_WIDTH, 0};
                SDL_FRect fR2 = {0, 0, (float)GAMECANVAS_WIDTH, 0};

                SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 64);

                for (int i = 0; i < counter_; i++) {
                    fR1.h = fR2.h = (float)(i * 4);
                    fR2.y = (float)(GAMECANVAS_HEIGHT - (i * 4));

                    SDL_RenderFillRect(renderer_, &fR1);
                    SDL_RenderFillRect(renderer_, &fR2);
                }

                if ((counter_ * 4) > GAMECANVAS_HEIGHT) {
                    finished_ = true;
                }
                break;
            }

            case FADE_RANDOM_SQUARE: {
                Uint32 now = SDL_GetTicks();
                if (squares_drawn_ < 50 && now - last_square_ticks_ >= 100) {
                    last_square_ticks_ = now;

                    SDL_FRect fRs = {0, 0, 32, 32};

                    // Crea un color al azar
                    Uint8 r = 255 * (rand() % 2);
                    Uint8 g = 255 * (rand() % 2);
                    Uint8 b = 255 * (rand() % 2);
                    SDL_SetRenderDrawColor(renderer_, r, g, b, 64);

                    // Dibujamos sobre el backbuffer
                    SDL_SetRenderTarget(renderer_, backbuffer_);

                    fRs.x = (float)(rand() % (GAMECANVAS_WIDTH - 32));
                    fRs.y = (float)(rand() % (GAMECANVAS_HEIGHT - 32));
                    SDL_RenderFillRect(renderer_, &fRs);

                    // Volvemos a usar el renderizador de forma normal
                    SDL_SetRenderTarget(renderer_, nullptr);

                    squares_drawn_++;
                }

                // Copiamos el backbuffer al renderizador
                SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);

                if (squares_drawn_ >= 50) {
                    finished_ = true;
                }
                break;
            }

            default:
                break;
        }
    }

    if (finished_) {
        SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 255);
        SDL_RenderClear(renderer_);
    }
}

// Actualiza las variables internas
void Fade::update() {
    if (enabled_) {
        counter_++;
    }
}

// Activa el fade
void Fade::activateFade() {
    enabled_ = true;
    finished_ = false;
    counter_ = 0;
    squares_drawn_ = 0;
    last_square_ticks_ = 0;
    fullscreen_done_ = false;
    r_ = r_original_;
    g_ = g_original_;
    b_ = b_original_;
}

// Comprueba si está activo
auto Fade::isEnabled() const -> bool {
    return enabled_;
}

// Comprueba si ha terminado la transicion
auto Fade::hasEnded() const -> bool {
    return finished_;
}

// Establece el tipo de fade
void Fade::setFadeType(Uint8 fade_type) {
    fade_type_ = fade_type;
}