#include "CS_Enemy_Firefly.h"
#include "CS_Exp.h"
#include "CS_PeSmoke.h"

CS_Enemy_Firefly::CS_Enemy_Firefly()
{
	ani.png = L"CS_CaveStoryMod";
	cbRect.enableCbRect = true;
	cbRect.enableSoild = true;
	cbRect.left = cbRect.right = cbRect.top = cbRect.bottom = 6;
	hp_max = hp = 4;
	dropExp = 4;
}

void CS_Enemy_Firefly::Init(std::weak_ptr<Entity> self)
{
	srcX = x;
	srcY = y;
	//设置光线
	auto wpeLight = std::make_shared<CS_PeLightFade>();
	peLight = wpeLight;
	gameFunc->SetEntity(shared_from_this(), wpeLight);
	
	auto wpeLightColor = std::make_shared<CS_PeLightFade>();;
	peLightColor = wpeLightColor;
	wpeLightColor->light.usingLight = false;
	wpeLightColor->color = RGBA(0x98, 0xff, 0, 0x10);
	gameFunc->SetEntity(shared_from_this(), wpeLightColor);

	wpeLight->SetRadius(4);
	wpeLightColor->SetRadius(4);
	wpeLight->last_x = wpeLight->x = x;
	wpeLight->last_y = wpeLight->y = y;
	wpeLightColor->last_x = wpeLightColor->x = x;
	wpeLightColor->last_y = wpeLightColor->y = y;
	Entity::Init(self);
}

void CS_Enemy_Firefly::Step()
{
	if (fly_counter > 0)
		fly_counter--;
	if (fly_counter == 0)
	{
		float speedX = Random(-0x300, 0x300) / ts;
		float speedY = Random(-0x100, 0x100) / ts;
		vx += speedX;
		vy += speedY;
		lr = vx < 0 ? 0 : 1;
		fly_counter = Random(10, 120);
	}
	const float resist = 0xa0 / ts / 2;
	vx /= 1.05f;
	vy /= 1.05f;
	if (abs(vx) < 0.01f)
		vx = 0;
	if (abs(vy) < 0.01f)
		vy = 0;
	//萤火虫不会飞低于自己的初始位置
	if (y > srcY)
		vy = -abs(vy);
	//清除最后一次碰撞结果
	Entity::ClearCollisionResult();
	//执行运动
	Entity::Step();
	//执行碰撞
	Entity::Collision();

	auto wpeLight = peLight.lock();
	if (wpeLight)
	{
		wpeLight->x = x;
		wpeLight->last_x = last_x;
		wpeLight->y = y;
		wpeLight->last_y = last_y;
	}
	auto wpeLightColor = peLightColor.lock();
	if (wpeLightColor)
	{
		wpeLightColor->x = x;
		wpeLightColor->last_x = last_x;
		wpeLightColor->y = y;
		wpeLightColor->last_y = last_y;
	}
}

void CS_Enemy_Firefly::SetState(int stateID, int lr)
{
	this->lr = lr;
	ani.sprite_index = L"ls_firefly_light";
}

std::weak_ptr<Entity> CS_Enemy_Firefly::BeginCaught(std::weak_ptr<Entity> e)
{
	return shared_from_this();
}

void CS_Enemy_Firefly::EndCaught(std::weak_ptr<Entity> e)
{
}

void CS_Enemy_Firefly::Destroy()
{
	auto wpeLight = peLight.lock();
	if (wpeLight)
		wpeLight->Destroy();
	auto wpeLightColor = peLightColor.lock();
	if (wpeLightColor)
		wpeLightColor->Destroy();
	Entity::Destroy();
}

std::shared_ptr<Entity> CreateCS_Enemy_Firefly()
{
	return std::make_shared<CS_Enemy_Firefly>();
}
