#include "sprite.h"

CSprite::CSprite()
{
}

CSprite::CSprite(SDL_Surface* img, float x, float y, int framerate, int maxframe)
{
    m_Img = img;
    m_FrameRate = framerate;
    m_MaxFrame = maxframe;
    m_X = x;
    m_Y = y;

    m_LastFrameTime = 0;
    m_CurrentFrame = 0;
    m_FrameRect.h = m_DestRect.h = m_CollisionRect.h = img->h;
    m_FrameRect.w = m_DestRect.w = m_CollisionRect.w = img->w / maxframe;

    m_CollisionRect.x = 0;
    m_CollisionRect.y = 0;

    m_NumOfLoops = 0;
    m_PlayOnce = false;
}

CSprite::~CSprite()
{
    //SDL_FreeSurface(m_Img);
}

void CSprite::Init(SDL_Surface* img, float x, float y, int framerate, int maxframe)
{
    m_Img = img;
    m_FrameRate = framerate;
    m_MaxFrame = maxframe;
    m_X = x;
    m_Y = y;

    m_LastFrameTime = 0;
    m_CurrentFrame = 0;
    m_FrameRect.h = m_DestRect.h = m_CollisionRect.h = img->h;
    m_FrameRect.w = m_DestRect.w = m_CollisionRect.w = img->w / maxframe;

    m_CollisionRect.x = 0;
    m_CollisionRect.y = 0;

    m_NumOfLoops = 0;
    m_PlayOnce = false;

}

void CSprite::Update( int deltaT )
{
    if (!(m_NumOfLoops >= 1 && m_PlayOnce))
    {
    m_LastFrameTime -= deltaT;
    if (m_LastFrameTime <= 0)
    {
        m_CurrentFrame++;
        m_LastFrameTime = m_FrameRate;
    }
    if (m_CurrentFrame >= m_MaxFrame)
    {
        m_NumOfLoops++;
        m_CurrentFrame = 0;
    }

    m_DestRect.x = (int)m_X;
    m_DestRect.y = (int)m_Y;

    m_FrameRect.x = m_CurrentFrame * m_FrameRect.w;
    }
}

void CSprite::Draw(SDL_Surface* screen)
{
    if (!(m_NumOfLoops >= 1 && m_PlayOnce))
        SDL_BlitSurface(m_Img, &m_FrameRect, screen, &m_DestRect);
}

bool CSprite::CheckCollision(CSprite* spr)
{
    int x0 = (int)m_X + m_CollisionRect.x;
    int y0 = (int)m_Y + m_CollisionRect.y;
    int x1 = (int)m_X + m_CollisionRect.w;
    int y1 = (int)m_Y + m_CollisionRect.h;

    int x2 = (int)spr->m_X + spr->m_CollisionRect.x;
    int y2 = (int)spr->m_Y + spr->m_CollisionRect.y;
    int x3 = (int)spr->m_X + spr->m_CollisionRect.w;
    int y3 = (int)spr->m_Y + spr->m_CollisionRect.h;

    return !(x1<x2 || x3<x0 || y1<y2 || y3<y0);

}
