////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: "CAnimation.cpp"
// Author: Alex Czarnopys (AC)
// Purpose: This is the source file for the CAnimation class.
//			The CAnimation class makes animations for objects.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CAnimation.h"
#include "CSGD_TextureManager.h"
#include "CGamePlayState.h"
#include "CHero.h"

CAnimation::CAnimation()
{
	SetImageID(-1);
	SetNumFrames(0);
	SetFrameTimer(0.0f);
	SetSpeed(0.0f);
	SetIsLooping(false);
	SetIsReverse(false);
	SetIsPlaying(false);
}
CAnimation::~CAnimation()
{
}

void CAnimation::CreateAnimation(char* szFileName, DWORD Transparent, tFrame FirstFrame, float fSpeed, 
								 bool bIsLooping, bool bIsReverse)
{
	SetCurFrame(FirstFrame);
	SetImageID(CSGD_TextureManager::GetInstance()->LoadTexture(szFileName, Transparent));
	SetNumFrames(1);
	SetSpeed(fSpeed);
	SetIsLooping(bIsLooping);
	SetIsReverse(bIsReverse);
	m_nFrameCur = 0;

	// Push first frame onto the list
	m_Frames.push_back(FirstFrame);
}

void CAnimation::AddFrame(tFrame NewFrame)
{
	SetNumFrames(GetNumFrames() + 1);
	// Push the new frame into the list
	m_Frames.push_back(NewFrame);
}
// play – call this once, resets the animation then plays
void CAnimation::Play(void)
{
	m_nFrameCur = 0;
	SetIsPlaying(true);
}
// stop – pause
void CAnimation::Stop(void)
{
	SetIsPlaying(false);
}
//	resume – unpause
void CAnimation::Resume(void)
{
	SetIsPlaying(true);
}
void CAnimation::Update(double dElapsedTime)
{
	if( !GetIsPlaying())
		return;
	// Check if enough time has passed to change frames.

	// Update timer
	SetFrameTimer(GetFrameTimer() + (dElapsedTime * GetSpeed()));

	if (GetFrameTimer() > GetCurFrame().fDuratrion)
	{
		SetFrameTimer(GetFrameTimer() - GetCurFrame().fDuratrion);
		m_nFrameCur++;

		/*if (GetIsLooping())
		{

		}
		else
		{*/
			// Check to see if the animation is over
		if (m_nFrameCur >= GetNumFrames())
		{
			Stop();
			m_nFrameCur = 0; // stay in bounds
		}
		/*}*/
		SetCurFrame(m_Frames[m_nFrameCur]);
	}
}
void CAnimation::Render(int nPosX, int nPosY, float fScaleX, float fScaleY, float fRotX, float fRotY, float fRot, DWORD color, float fZBuffer)
{
	 CSGD_TextureManager::GetInstance()->Draw(GetImageID(), (int)(nPosX - (GetCurFrame().ptAnchor.x - GetCurFrame().rSource.left) * fScaleX), 
		 (int)(nPosY - (GetCurFrame().ptAnchor.y - GetCurFrame().rSource.top) * fScaleY), fScaleX, fScaleY, &GetCurFrame().rSource,
		 fRotX, fRotY, fRot, color, fZBuffer);
}