#include "testcompare.h"

string TestCompareLoader::name="compare";

Ptr<VarDef> TestCompareLoader::variables[]=
{
	new VarDef("a","Defines first  number",VarDef::VAR_DOUBLE,"0"),
	new VarDef("b","Defines second number",VarDef::VAR_DOUBLE,"0"),
	new VarDef("c","Defines third  number",VarDef::VAR_DOUBLE,"0"),
	new VarDef("order","Defines sorting order, ascending if true, descending if false",VarDef::VAR_BOOL,"1"),

	0
};

Ptr<Command> TestCompareLoader::commands[]=
{
	new Command("get","Returns result"),
	new Command("reverse","Reverse sorting order and recount results."),

	0
};

void TestCompare::afterInstantiate()
{
	wasCounted=false;
}

void TestCompare::receiveMessage(TObject* mesg)
{
	if (mesg->typeOf(MesgCommand::type))
	{
		MesgCommand* command=(MesgCommand*)mesg;

		if (command->getName()=="get")
		{
			if (wasCounted)
			{
				for(int i=0;i<3;i++)
					cout<<(i+1)<<"."<<result[i]<<endl;
			}
			else
			{
				cout<<"UNDEFINED"<<endl;
			}
		}

		if (command->getName()=="reverse")
		{
			((VarBool*)getVariable("order"))->set(!toBool(getVariable("order")));
			run();
		}
	}
	
	if (mesg->typeOf(MesgVarChange::type))
	{
		wasCounted=false;
	}
}

void TestCompare::run()
{
	result[0]=toDouble(getVariable("a"));
	result[1]=toDouble(getVariable("b"));
	result[2]=toDouble(getVariable("c"));
	
	bool order=toBool(getVariable("order"));

	double extrem,xchg;
	int index;

	for(int j=0;j<2;j++)
	{
		extrem=result[j];
		index=j;
		for(int i=j+1;i<3;i++)
		{
			if (order)
			{
				if (extrem>result[i])
				{
					extrem=result[i];
					index=i;
				}
			}
			else
			{
				if (extrem<result[i])
				{
					extrem=result[i];
					index=i;
				}
			}
		}
		xchg=result[j];
		result[j]=extrem;
		result[index]=xchg;
	}

	wasCounted=true;
}
