#include <SDL2/SDL.h>
#include <iostream>
#include <strings.h>

#include "fmt/format.h"
#include "nodes/node.h"
#include "nodes/sprite.h"
#include "engine/input_manager.h"
#include "engine/util.h"
#include "engine/window.h"

Sprite::Sprite(const std::string& resourcePath) : Node()
{
    // Constructor
    //Util::log(INFO, resourcePath, __FILE__, __LINE__);
    gpuImage = GPU_LoadImage(resourcePath.c_str());
    target_ = Window::windowTarget;
}

Sprite::~Sprite() = default;

void Sprite::update()
{  
    // Call Baseclass update
    Node::update();

    // Call logic updates here

    // Call render for graphical elements
    render();
}

void Sprite::pollInputs()
{
    Node::pollInputs();
}

void Sprite::free(){
    GPU_FreeImage(gpuImage);
    gpuImage = nullptr;
    Node::free();
}

void Sprite::setImage(GPU_Image *img)
{
    GPU_FreeImage(gpuImage);
    gpuImage = img;
}

void Sprite::setImage(char *img_path)
{
    GPU_FreeImage(gpuImage);
    gpuImage = GPU_LoadImage(img_path);
}

void Sprite::getImage(GPU_Image *image)
{
    image = gpuImage;
}

void Sprite::render()
{
    if (gpuImage != nullptr)
    {
        if (visible)
        {
            Vec2 position_offset = worldPosition + localPosition;
            GPU_BlitTransform(gpuImage, nullptr, target_, position_offset.x, position_offset.y, angle * 180 / M_PI, scale.x, scale.y);
        }
    }
//    else
//    {
//        Util::log(ERROR, "Failed to render sprite, image resource is NULL", __FILE__, __LINE__);
//        exit(-1);
//    }
}