#include "splashes.h"
#include <cmath>

Splashes::Splashes(Game_Data *gd, QObject *parent) :
		QObject(parent)
{
	gameData = gd;
	nextId = 1;
}


bool Splashes::AddSplash(int srcId, QPointF pos)
{
	if (srcId < 0 || srcId >= gameData->srcSplashes.size())
	{
		qCritical("ERROR out of splashes range");
		return false;
	}
	srcSplashType src = gameData->srcSplashes.at(srcId);
	SplashType spl;// = gameData->srcAliens.at(srcId);
	spl.Id = nextId;
	spl.src = srcId;
	spl.TowerId = QPoint(-1,-1);
	spl.life = 0;
	spl.imgType = src.imgType;
	if (!gameData->map->Rect().contains(pos.toPoint()))
	{
		qCritical("ERROR splash out of map size");
		return false;
	}
	spl.pos = pos;
	spl.AlienId = -1;
	spl.angle = 0;
	spl.destination = pos;
	TriggerType trig;
	for(int i; i<src.triggerIndexes.size(); i++)
	{
		trig.timer = gameData->srTriggers.at(src.triggerIndexes.at(i)).timer;
		trig.src = src.triggerIndexes.at(i);
		spl.triggers.push_back(trig);
	}
	gameData->curSplashes.insert(spl.Id,spl);
	nextId++;
	return true;
}


void Splashes::AddSplash(srcSplashType src, int index, TowerType tw)
{
	SplashType spl;
	spl.Id = nextId;
	spl.TowerId = tw.pos;
	if (!gameData->curAliens.contains(tw.aim))
		qFatal("Error finding splash aim! Tower has nvalid aim!");
	if (src.autoControl)
		spl.AlienId = tw.aim;
	else
		spl.AlienId = -1;
	spl.destination = gameData->curAliens.value(tw.aim).pos;
	spl.angle = tw.angle;
	spl.pos = tw.pos; // FIXME: pos not in center or left-angle of tower
	spl.imgType = src.imgType;
	spl.life = 0;
	spl.src = index;
	TriggerType trig;
	for(int i; i<src.triggerIndexes.size(); i++)
	{
		trig.timer = gameData->players.at(tw.PlayerId)->srcTowers.at(tw.src).triggers.at(src.triggerIndexes.at(i)).timer;
		trig.src = src.triggerIndexes.at(i);
		spl.triggers.push_back(trig);
	}
	gameData->curSplashes.insert(spl.Id,spl);
	nextId++;
}


void Splashes::update()
{
	for (int i; i<gameData->curSplashes.size(); i++)
	{
		SplashType spl = gameData->curSplashes.values().at(i);
		bool isTowerSplash = false;
		srcSplashType src;
		TowerType tw;
		if (gameData->map->Rect().contains(spl.TowerId))
		{
			if (gameData->curTowers.contains(spl.TowerId))
			{
				tw = gameData->curTowers.value(spl.TowerId);
				src = gameData->players.at(tw.PlayerId)->srcTowers.at(tw.src).splashes.at(spl.src);
				isTowerSplash = true;
			} else {
				spl.TowerId = QPoint(-1,-1);
			}
		}
		if (!isTowerSplash)
			src = gameData->srcSplashes.at(spl.src);
		// TODO: calculate new angle and pos....
		// TODO: activate trigger and more...
	}
}
