#include "CS_AmLaser.h"
#include "CS_Enemy_LaserTrapBlade.h"

CS_AmLaser::CS_AmLaser()
{
	type = 2;
}

void CS_AmLaser::Init(std::weak_ptr<Entity> self)
{
	auto wsignt = std::make_shared<CS_Enemy_LaserTrapSight>();
	signt = wsignt;
	wsignt->x = x;
	wsignt->y = y;
	gameFunc->SetEntity(shared_from_this(), wsignt);
	Entity::Init(self);
}

void CS_AmLaser::Step()
{
	switch (stateID)
	{
	case 0://瞄准阶段
		{
			auto wsignt = signt.lock();
			if (wsignt)
			{
				//生成位置
				wsignt->x = x;
				wsignt->y = y;
				wsignt->TestDistance(x, y, cosf(angle * deg2rad), sinf(angle * deg2rad));
				//绘制瞄准线
				last_lineX = lineX;
				last_lineY = lineY;
				lineX = wsignt->x - x;
				lineY = wsignt->y - y;
			}
		}
		break;
	case 1:
		{
			auto wsignt = signt.lock();
			if (wsignt)
			{
				//生成位置
				wsignt->x = x;
				wsignt->y = y;
				wsignt->TestDistance(x, y, cosf(angle * deg2rad), sinf(angle * deg2rad));
				//放置抛射物
				float dirX = cosf(angle * deg2rad);
				float dirY = sinf(angle * deg2rad);
				float setX = x;
				float setY = y;
				float srcDx = setX - x;
				float srcDy = setY - y;
				float dstDx = wsignt->x - x;
				float dstDy = wsignt->y - y;
				while (srcDx * srcDx + srcDy * srcDy < dstDx * dstDx + dstDy * dstDy)
				{
					auto am = SetCS_Enemy_LaserTrapBlade(shared_from_this(), setX, setY);
					am->exist_time = 1;//只存在一回合
					setX += dirX * (am->cbRect.left + am->cbRect.right);
					setY += dirY * (am->cbRect.bottom + am->cbRect.top);
					srcDx = setX - x;
					srcDy = setY - y;
				}
				//绘制瞄准线
				last_lineX = lineX;
				last_lineY = lineY;
				lineX = wsignt->x - x;
				lineY = wsignt->y - y;
			}
			laser_color_counter++;
			if (laser_color_counter / 2 % 2 == 0)
				laser_color = RGBA(0xff, 0xff, 0, 0xff);
			else
				laser_color = RGBA(0xff, 0, 0, 0xff);
		}
		break;
	}
	angle += rotate_speed;
	//执行运动
	Entity::Step();
}

void CS_AmLaser::SetState(std::wstring stateName, int lr)
{
	if (stateName == L"laser_on")
	{
		stateID = 1;
	}
}

void CS_AmLaser::DeltaTime(float deltaTime)
{
	lineList.clear();
	fillList.clear();
	switch (stateID)
	{
	case 0://不绘制线条
		{
			float nowTargetX = lerp(last_lineX, lineX, deltaTime);
			float nowTargetY = lerp(last_lineY, lineY, deltaTime);
			AddLine(lineList, 0, 0, 0, RGBA(0xff, 0, 0, 0xff), nowTargetX, nowTargetY, RGBA(0xff, 0, 0, 0xff));
		}
		break;
	case 1://绘制瞄准镭射
		{
			float nowTargetX = lerp(last_lineX, lineX, deltaTime);
			float nowTargetY = lerp(last_lineY, lineY, deltaTime);
			AddFillLine(fillList, 0, 0, 0, laser_color, nowTargetX, nowTargetY, laser_color, 3);
		}
		break;
	}
	Entity::DeltaTime(deltaTime);
}

void CS_AmLaser::Destroy()
{
	auto wsignt = signt.lock();
	if (wsignt)
		wsignt->Destroy();
	Entity::Destroy();
}

std::shared_ptr<Entity> CreateCS_AmLaser()
{
	return std::make_shared<CS_AmLaser>();
}
