/** \file Track.cpp
 * \brief The implementation of the 'Track' class.
 */

#include "Track.h"

namespace OSkA
{
	Track::Track()
	{
		keyframes.resize(0);
	}

	Track::~Track()
	{
		for(int i=0; i<keyframes.size(); i++)
			delete keyframes[i];
		keyframes.clear();
	}

	void Track::addKeyframe(float time, Matrix* transform)
	{
		if(getKeyframesCount()==0)
		{
			keyframes.push_back(new Keyframe(time, transform));
		}
		else
		{
			keyframes.resize(getKeyframesCount()+1);
			int i;
			for(i=getKeyframesCount()-2; i>=0 && keyframes[i]->getTime()>time; i--)
				keyframes[i+1]=keyframes[i];
			keyframes[i+1]=new Keyframe(time, transform);
		}
	}

	int Track::getKeyframesCount()
	{
		return keyframes.size();
	}

	Keyframe* Track::getKeyframe(int index)
	{
		if(index >=getKeyframesCount())
			return new Keyframe();
		return keyframes[index];
	}

	Matrix* Track::getInterpolTransform(float time)
	{
		if(getKeyframesCount()==0)
			return new Matrix();
		if(time <=keyframes[0]->getTime())
			return keyframes[0]->getTransform();
		if(time >=keyframes[getKeyframesCount()-1]->getTime())
			return keyframes[getKeyframesCount()-1]->getTransform();

		int i=0;
		for(i=0; i<getKeyframesCount()-2 && time > keyframes[i+1]->getTime(); i++);

		float f1, f2, fw;
		fw=keyframes[i+1]->getTime()- keyframes[i]->getTime();
		f1=keyframes[i+1]->getTime()- time;
		f2=time - keyframes[i]->getTime();

		Matrix* trans=new Matrix();
		*trans=*keyframes[i]->getTransform()*(f1/fw)+ *keyframes[i+1]->getTransform()*(f2/fw);

		return trans;
	}
}
