#include "CS_Cage.h"

CS_Cage::CS_Cage()
{
	ani.png = L"CS_CaveStoryMod";
	ani.sprite_index = L"ls_cage";
	//启用碰撞
	cbRect.enableCbRect = true;
	cbRect.enableSoild = true;
	//设置碰撞框
	cbRect.left = 8; cbRect.right = 24;
	cbRect.top = 16;
	cbRect.bottom = 8;
}

void CS_Cage::Init(std::weak_ptr<Entity> self)
{
	stateGravity.Init(self);
	if (el.arg.length())
	{
		auto wel = gameFunc->GameCreateEntity(el.arg.c_str());
		eL = wel;
		wel->SetState(0, el.flag.lr ? 1 : 0);
		gameFunc->SetEntity(shared_from_this(), wel);
	}
	if (el.arg2.length())
	{
		auto wer = gameFunc->GameCreateEntity(el.arg2.c_str());
		eR = wer;
		wer->SetState(0, el.flag.lr ? 1 : 0);
		gameFunc->SetEntity(shared_from_this(), wer);
	}
	Entity::Init(self);
}

void CS_Cage::Step()
{
	//跟上移动平台
	Entity::BeginMovingPlatform();
	if (cbRect.cbBottom)
	{
		if (abs(vx > 0.001f))
			vx /= 2.0f;
		else
			vx = 0;
	}
	stateGravity.Step();
	//跟上移动平台
	Entity::EndMovingPlatform();
	//执行运动
	Entity::Step();
	//执行碰撞
	Entity::Collision();

	//关住笼子里的物体
	auto wel = eL.lock();
	if (wel)
	{
		wel->x = x;
		wel->y = y;
		wel->last_x = last_x;
		wel->last_y = last_y;
		wel->vx = 0;
		wel->vy = 0;
		wel->drawBeforeOtherEntity = true;
		wel->cbRect.cbBottom = true;
	}
	auto wer = eR.lock();
	if (wer)
	{
		wer->x = x + 16;
		wer->y = y;
		wer->last_x = last_x;
		wer->last_y = last_y;
		wer->vx = 0;
		wer->vy = 0;
		wer->drawBeforeOtherEntity = true;
		wer->cbRect.cbBottom = true;
	}
}

void CS_Cage::SetState(int stateID, int lr)
{
	//初始化
	anpTarget = lr;
}

void CS_Cage::SetState(std::wstring stateName, int lr)
{
	if (anpTarget == 0)
	{
		auto wel = eL.lock();
		if (wel)
			wel->SetState(stateName, lr);
	}
	else
	{
		auto wer = eR.lock();
		if (wer)
			wer->SetState(stateName, lr);
	}
}

void CS_Cage::Destroy()
{
	auto wel = eL.lock();
	if (wel)
		wel->Destroy();
	auto wer = eR.lock();
	if (wer)
		wer->Destroy();
	Entity::Destroy();
}

std::shared_ptr<Entity> CreateCS_Cage()
{
	return std::make_shared<CS_Cage>();
}
