#include "CS_FishTank.h"

CS_FishTank::CS_FishTank()
{
	ani.png = L"CS_CaveStoryMod";
	ani.sprite_index = L"ls_fishtank";
	//启用碰撞
	cbRect.enableCbRect = true;
	cbRect.enableSoild = true;
	//设置碰撞框
	cbRect.left = 8;
	cbRect.right = 74 - 8;
	cbRect.top = 8;
	cbRect.bottom = 8;
}

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

void CS_FishTank::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 we = eFish.lock();
	if (we)
	{
		we->x = x + (we->cbRect.left + we->cbRect.right) / 2 + 4;
		we->y = y - (we->cbRect.top + we->cbRect.bottom) / 2 - 4;
		we->last_x = last_x;
		we->last_y = last_y;
		we->vx = 0;
		we->vy = 0;
		we->drawBeforeOtherEntity = true;
		we->cbRect.cbBottom = true;
		we->cbRect.inWater = true;
	}
}

void CS_FishTank::SetState(int stateID, int lr)
{
	auto we = eFish.lock();
	if (we)
		we->SetState(stateID, lr);
}

void CS_FishTank::SetState(std::wstring stateName, int lr)
{
	auto we = eFish.lock();
	if (we)
	{
		if (stateName == L"clear")
		{
			//清除鱼缸绑定的实体
			we->Destroy();
			eFish.reset();
		}
		else
			we->SetState(stateName, lr);
	}
}

void CS_FishTank::Destroy()
{
	auto we = eFish.lock();
	if (we)
		we->Destroy();
	Entity::Destroy();
}

std::shared_ptr<Entity> CreateCS_FishTank()
{
	return std::make_shared<CS_FishTank>();
}
