#include "Engine.h"

cSprite::cSprite(std::string Name, int FrameCount, int Size) : cRenderObject(Name)
{
    m_FrameCount = FrameCount;
    m_Size = Size;
    m_Playing = m_EnableColourKey = false;
    m_FPS = 5;
    m_FrameNumer = m_XPos = m_YPos = m_CurrentFrame = m_ColourKey = 0;
    m_StartTime = m_CurrentTime = 0;
    m_SpriteSurface = NULL;

    play();
}

cSprite::~cSprite()
{
}

SDL_Surface* cSprite::loadSprite(std::string Filename, bool enableColourKey, int colourKey)
{
    m_EnableColourKey = enableColourKey;
    m_ColourKey = colourKey;

    m_SpriteSurface = g_TextureManager.loadSurface(Filename.c_str());

    if(m_EnableColourKey)
        SDL_SetColorKey(m_SpriteSurface, SDL_SRCCOLORKEY | SDL_RLEACCEL, m_ColourKey);

    return NULL;
}

void cSprite::update(SDL_Surface *Screen)
{
    if((Screen) && (m_SpriteSurface))
    {
        if(m_Playing)
            updateAnim();

         SDL_Rect SourceRct;
         SourceRct.x = m_CurrentFrame * m_Size; SourceRct.w = m_Size;
         SourceRct.y = 0; SourceRct.h = m_Size;

         SDL_Rect DestRect;
         DestRect.x = m_XPos; DestRect.w = m_Size;
         DestRect.y = m_YPos; DestRect.h = m_Size;

         SDL_BlitSurface(m_SpriteSurface, &SourceRct, Screen, &DestRect);
    }
}

void cSprite::updateAnim()
{
    m_CurrentTime = SDL_GetTicks() - m_StartTime;

    if(m_CurrentTime >= 1000)
    {
        m_StartTime = SDL_GetTicks();
        m_CurrentTime = 0;
        return;
    }

    float Scalar = (float) (m_CurrentTime / 1000.0f);
    float Frame = (float) (Scalar * m_FPS);

    if(m_FrameNumer != int(Frame))
    {
        m_FrameNumer = int(Frame);

        m_CurrentFrame++;

        if(m_CurrentFrame >= m_FrameCount)
            m_CurrentFrame = 0;
    }
}

bool cSprite::updateKey(SDLKey Key)
{
    return true;
}
