#include "CS_KanpaAniHook.h"
#include <PeSmog.h>

CS_KanpaAniHook::CS_KanpaAniHook(std::shared_ptr<Entity> parent)
{
	attackParent = parent;
	//初始动画设置
	ani.png = L"CS_CaveStoryMod";
	ani.sprite_index = L"am_fishhook2_90";
	//设置碰撞框
	cbRect.left = cbRect.right = cbRect.top = cbRect.bottom = 4;
	el.name = L"fishhook";
	x = parent->x - 13;
	y = parent->y + 0;
	last_lineX = lineX = 14;
	last_lineY = lineY = 0;
}

void CS_KanpaAniHook::Init(std::weak_ptr<Entity> self)
{
	stateGravity.Init(shared_from_this());
	stateGravity.SetGravityScale(0.5f);
	vx = 0x3c0 / ts;
	vy = -0x400 / ts;
	Entity::Init(self);
}

void CS_KanpaAniHook::Step()
{
	auto wattackParent = attackParent.lock();
	if (!wattackParent)
		return;

	auto wtarget = target.lock();
	if (wtarget)
	{
		vx = vy = 0;
		//执行运动
		Entity::Step();
		//移动到目标附近
		x = wtarget->x - 29;
		y = wtarget->y - 8;
		drawBeforeOtherEntity = true;
	}
	else
	{
		if (abs(vx) < 0.001f)
			vx = 0;
		else
			vx /= 1.01f;
		stateGravity.Step();
		AnimateStep();
		//执行运动
		Entity::Step();
	}
	last_lineX = lineX;
	last_lineY = lineY;
	lineX = wattackParent->x - x;
	lineY = wattackParent->y - y;
}

void CS_KanpaAniHook::DeltaTime(float deltaTime)
{
	auto wattackParent = attackParent.lock();
	if (!wattackParent)
		return;

	float nowPlayerX = lerp(last_lineX, lineX, deltaTime);
	float nowPlayerY = lerp(last_lineY, lineY, deltaTime);
	AddFillLine(fillList, 0, 0, 0, RGBA(0xff, 0xff, 0xff, 0xff), nowPlayerX + 18, nowPlayerY - 6, RGBA(0xff, 0xff, 0xff, 0xff), 1);
	Entity::DeltaTime(deltaTime);
}

void CS_KanpaAniHook::Leave()
{
	auto wattackParent = attackParent.lock();
	if (!wattackParent)
		return;

	auto pe = std::make_shared<PeSmog>();
	pe->x = x;
	pe->y = y;
	gameFunc->SetEntity(shared_from_this(), pe);
	Destroy();
}

void CS_KanpaAniHook::HookSetTarget(std::weak_ptr<Entity> target)
{
	this->target = target;
}

void CS_KanpaAniHook::AnimateStep()
{
	// 如果速度为零，保持当前精灵图不变
	if (vx == 0.0f && vy == 0.0f) 
		return;
	// 计算速度方向的角度（0-360度，0度指向右，顺时针增加）
	float angleRad = std::atan2(vy, vx);
	float angleDeg = angleRad * 180.0f / (float)(M_PI);  // 弧度转角度
	angleDeg = std::fmod(angleDeg + 360.0f, 360.0f);  // 确保在0-360范围内

	// 将角度映射到最近的45度倍数
	int nearest45 = static_cast<int>(std::round(angleDeg / 45.0f)) * 45;

	// 处理360度的情况（与0度相同）
	if (nearest45 == 360)
		nearest45 = 0;
	ani.sprite_index = L"am_fishhook2_" + std::to_wstring(nearest45);
}
