#include "CS_PuppyRunning.h"

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

void CS_PuppyRunning::Init(std::weak_ptr<Entity> self)
{
	stateSplash.Init(shared_from_this());
	Entity::Init(self);
}

void CS_PuppyRunning::Step()
{
	auto& ani_no = ani.image_index;
	stateSplash.Step();
	switch (act_no)
	{
	case 0:
		act_no = 1;
		ani_no = 0;
		ani_wait = 0;
		[[fallthrough]];
	case 1:
		if (Random(0, 120) == 10)
		{
			act_no = 2;
			act_wait = 0;
			ani_no = 1;
		}
		if (gameFunc->GetPlayerDistance)
		{
			auto wplayer = gameFunc->GetPlayerDistance(gameFunc->game, x, y).lock();
			if (wplayer)
			{
				if (x - 96 < wplayer->x && x + 96 > wplayer->x && y - 32 < wplayer->y && y + 16 > wplayer->y)
					lr = x > wplayer->x ? 0 : 1;

				if (x - 32 < wplayer->x && x + 32 > wplayer->x && y - 32 < wplayer->y && y + 16 > wplayer->y)
				{
					lr = x > wplayer->x ? 1 : 0;
					act_no = 10;
				}
			}
		}
		break;
	case 2:
		if (++act_wait > 8)
		{
			act_no = 1;
			ani_no = 0;
		}
		break;
	case 10:
		act_no = 11;
		ani_no = 4;
		ani_wait = 0;
		[[fallthrough]];
	case 11:
		if (cbRect.cbBottom)
		{
			if (++ani_wait > 2)
			{
				ani_wait = 0;
				++ani_no;
			}

			if (ani_no > 5)
				ani_no = 4;
		}
		else
		{
			ani_no = 5;
			ani_wait = 0;
		}
		if (cbRect.cbLeft)
		{
			vx = abs(vx) / 2;
			lr = 1;
		}
		if (cbRect.cbRight)
		{
			vx = -abs(vx) / 2;
			lr = 0;
		}
		if (lr == 0)
			vx -= 0x40 / ts;
		else
			vx += 0x40 / ts;

		if (vx > 0x5FF / ts)
			vx = 0x400 / ts;

		if (vx < -0x5FF / ts)
			vx = -0x400 / ts;
		break;
	}

	/*if (gKeyTrg & gKeyDown)
		bits |= NPC_INTERACTABLE;
	else
		bits &= ~NPC_INTERACTABLE;*/

	vy += 0x40 / ts;
	if (vy > 0x5FF / ts)
		vy = 0x5FF / ts;
	//清除最后一次碰撞结果
	Entity::ClearCollisionResult();
	//执行运动
	Entity::Step();
	//执行碰撞
	Entity::Collision();
	ani.sprite_index = lr == 0 ? L"ls_puppy_running_l" : L"ls_puppy_running_r";
}

void CS_PuppyRunning::SetState(int stateID, int lr)
{
	this->lr = lr;
	this->act_no = stateID;
	ani.sprite_index = lr == 0 ? L"ls_puppy_running_l" : L"ls_puppy_running_r";
}

std::shared_ptr<Entity> CreateCS_PuppyRunning()
{
	return std::make_shared<CS_PuppyRunning>();
}
