
#include "scheduler.h"



Task::Task(int fno, int tpe, GameObject* ob)
{
	frameno = fno;
	type = tpe;
	obj = ob;
}

void TaskList::connect(GameStatus* gstate, ObjectManager* m_ast, ObjectManager* m_sht, KeysPacket* kys)
{
	frameno     = gstate->frameno;
	m_asteroids = m_ast;
	m_shots     = m_sht;
	keys        = kys;
}

int TaskList::now()
{
	return this->frameno;
}

bool TaskList::execute()
{
	Task *currTask;
	bool success = false, hyperspace_pending = false;
	bool display_keys = false;
	
	if (display_keys) printf("Keys: ");
	
	// Wenn grad Hyperspace ansteht, lösche alle anderen Tasks
	for (int i = 0; i < tasklist.size(); i++)
	{
		currTask = &tasklist.at(i);
		if (currTask->frameno <= this->frameno && currTask->type == TASK_HYPERSPACE)
		{
			hyperspace_pending = true;
			break;
		}
	}
	
	if (hyperspace_pending)
	{
		for (int i = 0; i < tasklist.size(); i++)
		{
			currTask = &tasklist.at(i);
			if (currTask->frameno <= this->frameno && currTask->type != TASK_HYPERSPACE)
				tasklist.erase(tasklist.begin() + i--);
		}
	}
		
	for (int i = 0; i < tasklist.size(); i++)
	{
		currTask = &tasklist.at(i);
		if (currTask->frameno <= this->frameno)
		{
			switch (currTask->type)
			{
				case TASK_FIRE:
					keys->fire(true);
					if (display_keys) printf("F");
					success = true;
				break;
				case TASK_TURNLEFT:
					keys->left(true);
					if (display_keys) printf("L");
					success = true;
				break;
				case TASK_TURNRIGHT:
					keys->right(true);
					if (display_keys) printf("R");
					success = true;
				break;
				case TASK_HYPERSPACE:
					keys->hyperspace(true);
					if (display_keys) printf("H");
					success = true;
				break;
				case TASK_THRUST:
					keys->thrust(true);
					if (display_keys) printf("T");
					success = true;
				break;
				case TASK_NEWOBJECT:
					if (currTask->obj->objecttype == TYPE_ASTEROID)
					{
						m_asteroids->Add(currTask->obj);
						success = true;
					}
					if (currTask->obj->objecttype == TYPE_SHOT)
					{
						m_shots->Add(currTask->obj);
						success = true;
					}
				break;
			}
			
			tasklist.erase(tasklist.begin() + i--);
			
		} // end if
					
	} // end for
	
	if (display_keys) printf("\n");
	
	return success;
}

bool TaskList::plan(int type)
{
	return plan(now(), type);
}

bool TaskList::plan(int type, GameObject* obj)
{
	return plan(now(), type, obj);
}
			
bool TaskList::plan(int fno, int type)
{
	bool success = false;
	
	success = (type != TASK_NEWOBJECT);
	if (success)
		tasklist.push_back(Task(fno, type, NULL));

	return success;
}

bool TaskList::plan(int fno, int type, GameObject* obj)
{
	bool success = false;
	
	success = (type == TASK_NEWOBJECT);
	if (success)
		tasklist.push_back(Task(fno, type, obj));

	return success;
}	
