// Copyright (C) 2004-2009 Christoph Kubisch & Eike Decker
// This file is part of the "Luxinia Engine".
// For conditions of distribution and use, see copyright notice in luxiniapublicsdk.txt

#include "ma.h"
#include "luxmath/luxmath.h"
#include <time.h>

EXAnimOutputMA	g_EXOutMA;

booln EXAnimOutputMA::Export(EXAnimPTR ianim, std::ostream &file)
{
	if (!WriteHeader(file,ianim))
		return FALSE;

	uint trackcnt = EXAnim_getTrackCount(ianim);

	for (uint t = 0; t < trackcnt; t++){
		EXTrackPTR	itrack = EXAnim_getTrack(ianim,t);
		if(!WriteTrack(file,itrack))
			return FALSE;
	}

	return TRUE;
}

booln EXAnimOutputMA::WriteHeader(std::ostream &file,EXAnimPTR ianim)
{
	vfprint("MotionAnimationASCII\n",file);
	vfprint("Header{\n",file);
	vfprint("\tVersion: 100\n",file);

	char date[256];
	time_t aclock;
	time( &aclock );
	strftime(date,256,"%d/%m/%y",localtime( &aclock ));
	vfprint("\tDate: ",file);
	vfprint(date,file);
	vfprint("\n",file);

	strftime(date,256,"%H:%M:%S",localtime( &aclock ));
	vfprint("\tTime: ",file);
	vfprint(date,file);
	vfprint("\n",file);

	float maxtime = 0;
	uint trackcnt = EXAnim_getTrackCount(ianim);
	for (uint t = 0; t < trackcnt; t++){
		EXTrackPTR	itrack = EXAnim_getTrack(ianim,t);
		maxtime = MAX(EXTrack_getLength(itrack),maxtime);
	}

	vfprint("\tLength: ",file);
	vfprintfloat(maxtime,file);
	vfprint("\n}\n",file);

	return TRUE;
}

booln EXAnimOutputMA::WriteTrack(std::ostream &file,EXTrackPTR itrack)
{
	uint keycnt = EXTrack_getKeyCount(itrack);
	vfprint("Track{\n",file);

	vfprint("\tName: \"",file);
	vfprint(EXTrack_getName(itrack),file);
	vfprint("\"\n",file);

	vfprint("\tKeys: ",file);
	vfprintuint(keycnt,file);
	vfprint("\n",file);


	for (uint i = 0; i < keycnt; i++){
		EXPRSKeyPTR ikey = EXTrack_getKey(itrack,i);
		vfprint("\t",file);
		vfprintfloat(EXPRSKey_getTime(ikey),file);
		vfprint(" ",file);

		float	*pos	= EXPRSKey_getPosition(ikey);
		vfprintfloat(pos[0],file);	vfprint(" ",file);
		vfprintfloat(pos[1],file);	vfprint(" ",file);
		vfprintfloat(pos[2],file);	vfprint(" ",file);


		float	*rot	= EXPRSKey_getRotation(ikey);
		vfprintfloat(rot[0],file);	vfprint(" ",file);
		vfprintfloat(rot[1],file);	vfprint(" ",file);
		vfprintfloat(rot[2],file);	vfprint(" ",file);
		vfprintfloat(rot[3],file);	vfprint(" ",file);

		float	*scale	= EXPRSKey_getScale(ikey);
		vfprintfloat(scale[0],file);	vfprint(" ",file);
		vfprintfloat(scale[1],file);	vfprint(" ",file);
		vfprintfloat(scale[2],file);

		vfprint("\n",file);
	}
	vfprint("}\n",file);


	return TRUE;
}