#include "utils.h"
#include "application.h"
#include <math.h>
#include <string.h>

SDL_Texture* Utils_CreateTextureFromFile(const char *filename, SDL_Renderer *renderer)
{
    SDL_Surface *surface = SDL_LoadBMP(filename);
    Uint32 keyColor      = SDL_MapRGB(surface->format, 255, 0, 255);

    SDL_SetColorKey(surface, SDL_TRUE, keyColor);

    SDL_Texture *result = SDL_CreateTextureFromSurface(renderer, surface);

    SDL_FreeSurface(surface);

    return result;
}

point_t Utils_GetPositionFrame(const int frame, const int texture_width, const int frame_width)
{
    point_t result = Utils_GetPoint(0, 0);

    int fc = texture_width / frame_width;
    int fw = frame * frame_width;

    result.y = round(fw / texture_width);

    if (frame >= fc)
         result.x = frame - (fc * result.y);
    else result.x = fw / frame_width;

    return result;
}

int Utils_GetIndexFrame(const int fx, const int fy, const int texture_width, const int frame_width)
{
    int fc = texture_width / frame_width;

    return (fc * fy) + fx;
}

point_t Utils_GetPoint(int x, int y)
{
    point_t result;

    result.x = x;
    result.y = y;

    return result;
}

vector_t Utils_GetVector(float x, float y)
{
    vector_t result;

    result.x = x;
    result.y = y;

    return result;
}

SDL_Rect Utils_GetRect(int x, int y, int width, int height)
{
    SDL_Rect result;

    result.x = x;
    result.y = y;
    result.w = width;
    result.h = height;

    return result;
}

bool Utils_CompareStrings(const char *string1, const char *string2, const unsigned int length)
{
    bool result = false;

    int cmp = strncmp(string1, string2, length);

    if (cmp == 0)
        result = true;

    return result;
}

rgba_t Utils_GetRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
    rgba_t result;

    result.r = r;
    result.g = g;
    result.b = b;
    result.a = a;

    return result;
}

int Utils_GetRandomRange(const int min, const int max)
{
    int result = rand() % (max - min + 1) + min;

    return result;
}

bool Utils_PointInCircle(const vector_t point, const vector_t center, const float radius)
{
    bool result = false;

    float f = pow(point.x - center.x, 2) + pow(point.y - center.y ,2);

    if (f <= pow(radius, 2))
        result = true;

    return result;
}
