#include "SysLocalCamera_H.h"
#include "SysNull.h"
void SysLocalCamera_H::Step()
{
	if (!gameFunc->SetLocalCamera)
		return;
	if (lr == 0)
	{
		//检查是否有玩家在这块区域内
		bool bSet = false;
		auto& allPlayer = *gameFunc->GetGlobalEntityTable(gameFunc->game);
		for (auto& p : allPlayer)
		{
			auto wplayer = p.second.lock();
			if (wplayer && !wplayer->enableAI && !wplayer->hide && wplayer->el.name != SYSNULL_CREATENAME)
			{
				if (Touch(wplayer))
				{
					bSet = true;
					if (leftLimit != -1)
						x = max(leftLimit, wplayer->x);
					else
						x = wplayer->x;
					if (rightLimit != -1)
						x = min(rightLimit, wplayer->x);
					else
						x = wplayer->x;
					break;
				}
			}
		}
		if (bSet)
		{
			//聚焦到该Npc
			gameFunc->SetLocalCamera(gameFunc->game, shared_from_this(), 16);
		}
		else
		{
			//取消该单位的聚焦
			gameFunc->UnsetLocalCamera(gameFunc->game, shared_from_this());
			auto wplayer = gameFunc->GetPlayerDistance(gameFunc->game, x, y).lock();
			if (wplayer)
			{
				if (leftLimit != -1)
					x = max(leftLimit, wplayer->x);
				else
					x = wplayer->x;
				if (rightLimit != -1)
					x = min(rightLimit, wplayer->x);
				else
					x = wplayer->x;
			}
		}
	}
}

void SysLocalCamera_H::SetState(std::wstring stateName, int lr)
{
	if (stateName == L"disable_focus")
	{
		//取消该单位的聚焦
		gameFunc->UnsetLocalCamera(gameFunc->game, shared_from_this());
		this->lr = 1;
	}
	else if (stateName == L"enable_focus")
	{
		this->lr = 0;
	}
}

void SysLocalCamera_H::Init(std::weak_ptr<Entity> self)
{
	if (el.arg.length() && ParseInts(el.arg.c_str(), argbuff))
	{
		if (argbuff.size() == 4)
		{
			cbRect.left = 16.0f * argbuff[0];
			cbRect.right = 16.0f * argbuff[1];
			cbRect.top = 16.0f * argbuff[2];
			cbRect.bottom = 16.0f * argbuff[3];
		}
	}
	if (el.arg2.length() && ParseInts(el.arg2.c_str(), argbuff))
	{
		if (argbuff.size() == 2)
		{
			leftLimit = 16.0f * argbuff[0];
			rightLimit = 16.0f * argbuff[1];
		}
	}
	Entity::Init(self);
}

std::shared_ptr<Entity> CreateSysLocalCamera_H()
{
	return std::make_shared<SysLocalCamera_H>();
}
