#include "ImageAnimation.hpp"
#include "Debug.hpp"
#include "elements/Transformable.hpp"
#include "utils/Time.hpp"

TSE::ImageAnimation::ImageAnimation()
{
}

void TSE::ImageAnimation::SetAnimationSet(ImageAnimationSet *set)
{
    animations[set->Name] = set;
}

void TSE::ImageAnimation::SetAnimationSet(string name, ImageAnimationSet *set)
{
    animations[name] = set;
}

void TSE::ImageAnimation::StartAnimation(const string name)
{
    currentAnimation = name;
    frame = 0;
    deltatime = 0;
}

int TSE::ImageAnimation::GetImageAnimationSetCount()
{
    return animations.size();
}

TSE::ImageAnimationSet *TSE::ImageAnimation::GetImageAnimationAt(int &i)
{
    auto it = animations.begin();
    for (int j = 0; j < i; j++)
    {
        it++;
    }
    return it->second;
}

TSE::string &TSE::ImageAnimation::GetCurrentAnimation()
{
    return currentAnimation;
}

int &TSE::ImageAnimation::GetCurrentFrame()
{
    return frame;
}

float &TSE::ImageAnimation::GetDeltaTime()
{
    return deltatime;
}

void TSE::ImageAnimation::RemoveAnimationSet(std::string &name)
{
    if(currentAnimation == name)
    {
        currentAnimation = "";
        frame = 0;
        deltatime = 0;
    }
    animations.erase(name);
}

void TSE::ImageAnimation::OnUpdate()
{
    if(currentAnimation == "") return;
    if(animations.find(currentAnimation) == animations.end())
    {
        TSE_ERROR("AnimationSet " + currentAnimation + " not found.");
        return;
    }
    deltatime += Time::deltaTime();
    if(deltatime >= animations[currentAnimation]->frameTime)
    {
        deltatime = 0;
        frame++;
        if(frame >= animations[currentAnimation]->Sprites.size())
        {
            frame = 0;
        }
        Image* img = (Image*)baseObject->GetBehaviourScript(IMAGE);
        img->SetSprite(*animations[currentAnimation]->Sprites[frame]);
    }
}
