#include "CS_GiantMagicBall.h"
#include "CS_PeEnergyCharge.h"
#include "CS_PeEnergyChargeFrom.h"
CS_GiantMagicBall::CS_GiantMagicBall()
{
}

void CS_GiantMagicBall::Step()
{
	fillList_set_last.swap(fillList_set);
	int index = 0;
	//绘制外部的渐变大紫圆
	float fade_r = 48 + 8 * sinf(action_timecounter * deg2rad);
	//action_timecounter++;
	index += AddFillFadeCircle(fillList_set, index, inner_r + fade_r, fade_r, RGBA(0xf8, 0x4b, 0xff, 0xff));
	//绘制中心的白圆
	index += AddFillFadeCircle(fillList_set, index, inner_r * 0.8f, 0, RGBA(0xff, 0xff, 0xff, 0xff));
	if (bCharge || fade_counter > 0)
	{
		if (bCharge)
		{
			charge_counter++;
			if (charge_counter % 2 == 0)
			{
				SetCS_PeEnergyCharge(shared_from_this(), 16 * 5);
				auto wenergyFrom = energyFrom.lock();
				if (wenergyFrom && (charge_counter % 8 == 0))
					SetCS_PeEnergyChargeFrom(shared_from_this(), wenergyFrom);
			}
		}
		else if(bStop)
		{
			if (fade_counter > 0)
				fade_counter--;
		}
		inner_r += inner_inc;
	}
	if (bAccDown)
	{
		vy += 0x10 / ts;
	}
	//执行运动
	Entity::Step();
}

void CS_GiantMagicBall::DeltaTime(float deltaTime)
{
	if (fillList.size() < fillList_set_last.size())
		fillList.resize(fillList_set_last.size());
	for (int i = 0; i < fillList_set_last.size(); i++)
	{
		auto& dst = fillList[i];
		auto& src_last = fillList_set_last[i];
		auto& src = fillList_set[i];
		dst.x = lerp(src_last.x, src.x, deltaTime);
		dst.y = lerp(src_last.y, src.y, deltaTime);
		dst.c = src.c;
	}
	Entity::DeltaTime(deltaTime);
}

void CS_GiantMagicBall::SetState(std::wstring stateName, int lr)
{
	if (bSetTarget)
	{
		bSetTarget = false;
		std::shared_ptr<Entity> wtarget;
		auto& allRes = *gameFunc->GetLoadedEntity(gameFunc->entityRes);
		EntityLayer* eLayer = nullptr;
		for (auto& res : allRes)
		{
			if (res.first->layerType == 0)
			{
				eLayer = &res.second;
				break;
			}
		}
		if (eLayer)
		{
			bool bFound = false;
			//在全局实体里寻找
			auto& allPlayer = *gameFunc->GetGlobalEntityTable(gameFunc->game);
			for (auto& p : allPlayer)
			{
				auto wplayer = p.second.lock();
				if (wplayer && wplayer->el.name == stateName)
				{
					wtarget = wplayer;
					bFound = true;
					break;
				}
			}
			//在地图实体层里寻找
			if (!bFound)
			{
				for (auto& e : eLayer->Ls)
				{
					if (e->el.eventName == stateName)
					{
						wtarget = e;
						break;
					}
				}
			}
		}
		if (wtarget)
		{
			energyFrom = wtarget;
		}
	}
	else
	{
		if (stateName == L"charge")
		{
			bStop = false;
			bCharge = true;
			inner_inc = 0x80 / ts;
			fade_counter = 60;
		}
		else if (stateName == L"stop")
		{
			bCharge = false;
			bStop = true;
		}
		else if (stateName == L"set_charge_energy_target")
		{
			bSetTarget = true;
		}
		else if (stateName == L"down")
		{
			bAccDown = true;
		}
	}
}

std::shared_ptr<Entity> CreateCS_GiantMagicBall()
{
	return std::make_shared<CS_GiantMagicBall>();
}
