#include "CS_AmMissile.h"
#include "CS_PeBooster.h"
#include "CS_PeSmoke.h"
CS_AmMissile::CS_AmMissile(std::shared_ptr<Entity> parent)
{
	type = 2;
	attackParent = parent;
	lr = parent->lr;
	//启用碰撞
	cbRect.enableCbRect = true;
	cbRect.left = cbRect.right = 6;
	cbRect.bottom = cbRect.top = 4;
	hp_max = hp = 10;
	dropExp = 3;
	//设置动画
	ani.png = L"CS_CaveStoryMod";
	ani.sprite_index = lr == 0 ? L"am_missile_l" : L"am_missile_r";
}

void CS_AmMissile::Step()
{
	auto& ani_no = ani.image_index;
	BOOL bHit = FALSE;

	if (lr == 0 && cbRect.cbLeft)
		bHit = TRUE;
	if (lr != 0 && cbRect.cbRight)
		bHit = TRUE;

	if (bHit)
	{
		gameFunc->PlaySound(L"CS_044_missile_hit");
		SetCS_PeSmoke(shared_from_this(), x, y, 3);
		Destroy();
		return;
	}
	switch (act_no)
	{
	case 0:
		act_no = 1;
		if (lr == 0)
			vx = (float)Random(1, 2);
		else
			vx = (float)Random(-2, -1);
		vy = (float)Random(-2, 0);
		[[fallthrough]];
	case 1:
		++count1;
		if (lr == 0)
		{
			vx -= 0x20 / ts;
			if (count1 % 3 == 1)
			{
				auto pe = std::make_shared<CS_PeBooster>(lr, 0);
				pe->x = x + 8;
				pe->y = y;
				gameFunc->SetEntity(shared_from_this(), pe);
			}
		}
		else
		{
			vx += 0x20 / ts;
			if (count1 % 3 == 1)
			{
				auto pe = std::make_shared<CS_PeBooster>(lr, 0);
				pe->x = x - 8;
				pe->y = y;
				gameFunc->SetEntity(shared_from_this(), pe);
			}
				
		}
		if (count1 < 50)
		{
			if (gameFunc->GetPlayerDistance)
			{
				auto wplayer = gameFunc->GetPlayerDistance(gameFunc->game, x, y).lock();
				if (wplayer)
				{
					if (y < wplayer->y)
						vy += 0x20 / ts;
					else
						vy -= 0x20 / ts;
				}
			}
		}
		else
		{
			vy = 0;
		}
		if (++ani_no > 1)
			ani_no = 0;
		break;
	}
	if (vx < -0x400 / ts)
		vx = -0x600 / ts;
	if (vx > 0x400 / ts)
		vx = 0x600 / ts;
	//清除最后一次碰撞结果
	Entity::ClearCollisionResult();
	//执行运动
	Entity::Step();
	//执行碰撞
	Entity::Collision();
}

void CS_AmMissile::Attack(std::weak_ptr<Entity> dst, int* outDamage, float* outAngle, bool* outTakedown, int* outElemType, float* outShockForce, float* outHeavy)
{
	*outDamage = 5;
	auto wdst = dst.lock();
	if (wdst)
	{
		if (wdst->lr == 0)
		{
			*outAngle = 315;
		}
		else
		{
			*outAngle = 225;
		}
	}
	*outTakedown = true;
	*outElemType = 0;
	*outShockForce = 0x200 / ts;
	*outHeavy = 2;
}

bool CS_AmMissile::Hurt(std::weak_ptr<Entity> src, int getDamage, float angle, bool bTakedown, int elemType, float shockForce, float heavy, int* outRealDamage)
{
	if (getDamage == 0)
		return false;
	*outRealDamage = getDamage;
	hp -= getDamage;
	if (hp > 0)
	{
		gameFunc->PlaySound(L"CS_051_enemy_hurt");
	}
	else
	{
		gameFunc->PlaySound(L"CS_071_little_crash");
		//创建云团
		SetCS_PeSmokeLarge(shared_from_this(), x, y);
		hp = 0;
		Destroy();
	}
	return true;
}

void SetCS_AmMissile(std::shared_ptr<Entity> parent, float x, float y, float vx, float vy)
{
	auto am = std::make_shared<CS_AmMissile>(parent);
	am->x = x;
	am->y = y;
	am->vx = vx;
	am->vy = vy;
	parent->gameFunc->SetEntity(parent, am);
}
