#include "CS_Bubble_Catcher.h"

CS_Bubble_Catcher::CS_Bubble_Catcher()
{
	ani.png = L"CS_CaveStoryMod";
	ani.sprite_index = L"ls_bubble_catcher";
	topDraw = true;
}

void CS_Bubble_Catcher::Step()
{
	const float speed = 0x450 / ts;
	switch (stateID)
	{
	case 0:
		{
			auto wtarget = target.lock();
			if (wtarget)
			{
				float vec_x = wtarget->x - x;
				float vec_y = wtarget->y - y;
				auto vec = XMVector2Normalize(XMVectorSet(vec_x, vec_y, 0, 0));
				float dir_vx = XMVectorGetX(vec);
				float dir_vy = XMVectorGetY(vec);
				vx = dir_vx * speed;
				vy = dir_vy * speed;
			}
		}
		break;
	case 1://转弯上升
		if (lr == 0)
			vx -= 0x10 / ts;
		else if (lr == 1)
			vx += 0x10 / ts;
		vy -= 0x10 / ts;
		if (vx > speed)
			vx = speed;
		if (vx < -speed)
			vx = -speed;
		if (vy > speed)
			vy = speed;
		if (vy < -speed)
			vy = -speed;
		break;
	}
	//执行运动
	Entity::Step();
}

void CS_Bubble_Catcher::SetState(std::wstring stateName, int lr)
{
	if (bSetTarget)
	{
		bSetTarget = false;
		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)
				{
					target = wplayer;
					bFound = true;
					break;
				}
			}
			//在地图实体层里寻找
			if (!bFound)
			{
				for (auto& e : eLayer->Ls)
				{
					if (e->el.eventName == stateName)
					{
						target = e;
						break;
					}
				}
			}
		}
	}
	else
	{
		if (stateName == L"normal" || stateName == L"empty")
		{
			stateID = 0;
			ani.sprite_index = L"ls_bubble_catcher";
		}
		else if (stateName == L"set_target")
			bSetTarget = true;
		else if (stateName == L"top_draw_false")
			topDraw = false;
		else if (stateName == L"caught_toroko")
		{
			stateID = 0;
			ani.sprite_index = lr == 0 ? L"ls_bubble_catcher_toroko_l" : L"ls_bubble_catcher_toroko_r";
		}
		else if (stateName == L"caught_jack")
		{
			stateID = 0;
			ani.sprite_index = lr == 0 ? L"ls_bubble_catcher_jack_l" : L"ls_bubble_catcher_jack_r";
		}
		else if (stateName == L"caught_santa")
		{
			stateID = 0;
			ani.sprite_index = lr == 0 ? L"ls_bubble_catcher_santa_l" : L"ls_bubble_catcher_santa_r";
		}
		else if (stateName == L"turn")
		{
			stateID = 1;
			this->lr = lr;
		}
	}
}

std::shared_ptr<Entity> CreateCS_Bubble_Catcher()
{
	return std::make_shared<CS_Bubble_Catcher>();
}
