#include "CS_PuppyBarking.h"

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

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

void CS_PuppyBarking::Step()
{
	auto& ani_no = ani.image_index;
	stateSplash.Step();
	if (act_no < 100)
	{
		if (gameFunc->GetPlayerDistance)
		{
			auto wplayer = gameFunc->GetPlayerDistance(gameFunc->game, x, y).lock();
			if (wplayer)
			{
				if (wplayer->x < x)
					lr = 0;
				else
					lr = 1;
			}
		}
	}
	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;
		}
		{
			bool b = false;
			if (gameFunc->GetPlayerDistance)
			{
				auto wplayer = gameFunc->GetPlayerDistance(gameFunc->game, x, y).lock();
				if (wplayer)
				{
					if (x - 64 < wplayer->x && x + 64 > wplayer->x && y - 16 < wplayer->y && y + 16 > wplayer->y)
					{
						b = true;
						if (++ani_wait > 4)
						{
							ani_wait = 0;
							++ani_no;
						}
						if (ani_no > 4)
							ani_no = 2;
						if (ani_no == 4 && ani_wait == 0)
							gameFunc->PlaySound(L"CS_105_puppy_bark");
					}
				}
			}
			if (!b)
			{
				if (ani_no == 4)
					ani_no = 2;
			}
		}
		break;
	case 2:
		if (++act_wait > 8)
		{
			act_no = 1;
			ani_no = 0;
		}
		break;
	case 10:
		act_no = 11;
		ani_no = 0;
		ani_wait = 0;
		[[fallthrough]];
	case 11:
		if (Random(0, 120) == 10)
		{
			act_no = 12;
			act_wait = 0;
			ani_no = 1;
		}
		break;
	case 12:
		if (++act_wait > 8)
		{
			act_no = 11;
			ani_no = 0;
		}
		break;
	case 100:
		act_no = 101;
		count1 = 0;
		[[fallthrough]];
	case 101:
		if (++ani_wait > 4)
		{
			ani_wait = 0;
			++ani_no;
		}
		if (ani_no > 4)
		{
			if (count1 < 3)
			{
				ani_no = 2;
				++count1;
			}
			else
			{
				ani_no = 0;
				count1 = 0;
			}
		}
		if (ani_no == 4 && ani_wait == 0)
			gameFunc->PlaySound(L"CS_105_puppy_bark");
		break;
	case 120:
		ani_no = 0;
		break;
	}
	vy += 0x40 / ts;
	if (vy > 0x5FF / ts)
		vy = 0x5FF / ts;
	//清除最后一次碰撞结果
	Entity::ClearCollisionResult();
	//执行运动
	Entity::Step();
	//执行碰撞
	Entity::Collision();
	ani.sprite_index = lr == 0 ? L"ls_puppy_barking_l" : L"ls_puppy_barking_r";
}

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

std::shared_ptr<Entity> CreateCS_PuppyBarking()
{
	return std::make_shared<CS_PuppyBarking>();
}
