#include "notify.h"
#include <string>
#include <stdio.h>
#include <iostream>

// Constructor
Notify::Notify(SDL_Renderer *renderer, string iconFile, string bitmapFile, string textFile, string soundFile, options_t *options)
{
    // Inicializa variables
    this->renderer = renderer;
    this->options = options;
    bgColor = options->notifications.color;
    waitTime = 300;

    // Crea objetos
    iconTexture = new Texture(renderer, iconFile);
    text = new Text(textFile, bitmapFile, renderer);
    sound = JA_LoadSound(soundFile.c_str());
}

// Destructor
Notify::~Notify()
{
    // Libera la memoria de los objetos
    if (iconTexture != nullptr)
    {
        delete iconTexture;
    }
    if (text != nullptr)
    {
        delete text;
    }
    JA_DeleteSound(sound);

    for (auto notification : notifications)
    {
        if (notification.sprite != nullptr)
        {
            delete notification.sprite;
        }
        if (notification.texture != nullptr)
        {
            delete notification.texture;
        }
    }
}

// Dibuja las notificaciones por pantalla
void Notify::render()
{
    for (int i = (int)notifications.size() - 1; i >= 0; --i)
    {
        notifications[i].sprite->render();
    }
}

// Actualiza el estado de las notificaiones
void Notify::update()
{
    for (int i = 0; i < (int)notifications.size(); ++i)
    {
        notifications[i].counter++;

        // Comprueba los estados
        if (notifications[i].state == ns_rising)
        {
            const float step = ((float)notifications[i].counter / notifications[i].travelDist);
            const int alpha = 255 * step;

            if (options->notifications.posV == pos_top)
            {
                notifications[i].rect.y++;
            }
            else
            {
                notifications[i].rect.y--;
            }
            notifications[i].texture->setAlpha(alpha);

            if (notifications[i].rect.y == notifications[i].y)
            {
                notifications[i].state = ns_stay;
                notifications[i].texture->setAlpha(255);
                notifications[i].counter = 0;
            }
        }

        else if (notifications[i].state == ns_stay)
        {
            if (notifications[i].counter == waitTime)
            {
                notifications[i].state = ns_vanishing;
                notifications[i].counter = 0;
            }
        }
        else if (notifications[i].state == ns_vanishing)
        {

            const float step = (notifications[i].counter / (float)notifications[i].travelDist);
            const int alpha = 255 * (1 - step);

            if (options->notifications.posV == pos_top)
            {
                notifications[i].rect.y--;
            }
            else
            {
                notifications[i].rect.y++;
            }
            notifications[i].texture->setAlpha(alpha);

            if (notifications[i].rect.y == notifications[i].y - notifications[i].travelDist)
            {
                notifications[i].state = ns_finished;
            }
        }

        notifications[i].sprite->setRect(notifications[i].rect);
    }

    clearFinishedNotifications();
}

// Elimina las notificaciones finalizadas
void Notify::clearFinishedNotifications()
{
    for (int i = (int)notifications.size() - 1; i >= 0; --i)
    {
        if (notifications[i].state == ns_finished)
        {
            if (notifications[i].sprite != nullptr)
            {
                delete notifications[i].sprite;
            }
            if (notifications[i].texture != nullptr)
            {
                delete notifications[i].texture;
            }
            notifications.erase(notifications.begin() + i);
        }
    }
}

// Muestra una notificación de texto por pantalla;
void Notify::showText(string text1, string text2, int icon)
{
    // Inicializa variables
    const int iconSize = 16;
    const int padding = text->getCharacterSize();
    const int iconSpace = icon >= 0 ? iconSize + padding : 0;
    const string txt = text1.length() > text2.length() ? text1 : text2;
    const int width = text->lenght(txt) + (padding * 2) + iconSpace;
    const int height = (text->getCharacterSize() * 2) + (padding * 2);

    // Posición horizontal
    int despH = 0;
    if (options->notifications.posH == pos_left)
    {
        despH = padding;
    }
    else if (options->notifications.posH == pos_middle)
    {
        despH = ((options->screen.nativeWidth * options->screen.windowZoom) / 2 - (width / 2));
    }
    else
    {
        despH = (options->screen.nativeWidth * options->screen.windowZoom) - width - padding;
    }

    // Posición vertical
    int despV = 0;
    if (options->notifications.posV == pos_top)
    {
        despV = padding;
    }
    else
    {
        despV = (options->screen.nativeHeight * options->screen.windowZoom) - height - padding;
    }

    const int travelDist = height + padding;

    // Offset
    int offset = 0;
    if (options->notifications.posV == pos_top)
    {
        offset = (int)notifications.size() > 0 ? notifications.back().y + travelDist : despV;
    }
    else
    {
        offset = (int)notifications.size() > 0 ? notifications.back().y - travelDist : despV;
    }

    // Crea la notificacion
    notification_t n;

    // Inicializa variables
    n.y = offset;
    n.travelDist = travelDist;
    n.counter = 0;
    n.state = ns_rising;
    n.text1 = text1;
    n.text2 = text2;
    if (options->notifications.posV == pos_top)
    {
        n.rect = {despH, offset - travelDist, width, height};
    }
    else
    {
        n.rect = {despH, offset + travelDist, width, height};
    }

    // Crea la textura
    n.texture = new Texture(renderer);
    n.texture->createBlank(renderer, width, height, SDL_TEXTUREACCESS_TARGET);
    n.texture->setBlendMode(SDL_BLENDMODE_BLEND);

    // Prepara para dibujar en la textura
    n.texture->setAsRenderTarget(renderer);

    // Dibuja el fondo de la notificación
    SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
    SDL_Rect rect;
    rect = {4, 0, width - (4 * 2), height};
    SDL_RenderFillRect(renderer, &rect);

    rect = {4 / 2, 1, width - 4, height - 2};
    SDL_RenderFillRect(renderer, &rect);

    rect = {1, 4 / 2, width - 2, height - 4};
    SDL_RenderFillRect(renderer, &rect);

    rect = {0, 4, width, height - (4 * 2)};
    SDL_RenderFillRect(renderer, &rect);

    // Dibuja el icono de la notificación
    if (icon >= 0)
    {
        Sprite *sp = new Sprite({0, 0, iconSize, iconSize}, iconTexture, renderer);
        sp->setPos({padding, padding, iconSize, iconSize});
        sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize});
        sp->render();
        delete sp;
    }

    // Escribe el texto de la notificación
    color_t color = {255, 255, 255};
    if (text2 != "")
    { // Dos lineas de texto
        text->writeColored(padding + iconSpace, padding, text1, color);
        text->writeColored(padding + iconSpace, padding + text->getCharacterSize() + 1, text2, color);
    }
    else
    { // Una linea de texto
        text->writeColored(padding + iconSpace, (height / 2) - (text->getCharacterSize() / 2), text1, color);
    }

    // Deja de dibujar en la textura
    SDL_SetRenderTarget(renderer, nullptr);

    // Crea el sprite de la notificación
    n.sprite = new Sprite(n.rect, n.texture, renderer);

    // Añade la notificación a la lista
    notifications.push_back(n);

    // Reproduce el sonido de la notificación
    if (options->notifications.sound)
    {
        JA_PlaySound(sound);
    }
}

// Indica si hay notificaciones activas
bool Notify::active()
{
    if ((int)notifications.size() > 0)
    {
        return true;
    }

    return false;
}