#include "AiStation.h"

AiStation::AiStation()
{
	ani.png = L"sys_obj";
	ani.sprite_index = L"ai_station_node";
}

void AiStation::SetState(int stateID, int lr)
{
	this->lr = lr;
	if (bSetStationID)
	{
		bSetStationID = false;
		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(), stationID);
			upper = stationID;
			if (stationID.empty())
				return;
			//根没有上级
			if (stationID.size() == 1 && stationID.front() == 0)
				return;
			//计算自己的上级
			if (stationID.back() == 0)
				upper.pop_back();
			else
				upper.back() -= 1;
		}
		if (el.arg3.length() && ParseInts(el.arg3.c_str(), argbuff))
		{
			if (!argbuff.empty())
				stationType = argbuff.front();
		}
	}
	ani.sprite_index = lr == 0 ? L"ai_station_node" : L"ai_station_extend";
}

void AiStation::Step()
{
	if (stationID.empty())
		return;
	//寻找自己的上级实体
	if (bFindUpperEntity)
	{
		bFindUpperEntity = false;
		bool bRoot = stationID.size() == 1 && stationID.front() == 0;
		if (entityLayer && !bRoot)
		{
			EntityLayer* layer = (EntityLayer*)entityLayer;
			for (auto& p : layer->Ls)
			{
				if (p->lr != 0)
					continue;
				if (p->el.name == AISTATION_CREATENAME)
				{
					auto e = std::static_pointer_cast<AiStation> (p);
					if (e->stationID == upper)
					{
						upperEntity = e;
						break;
					}
				}
			}
		}
		//其他初始化
		if (gameFunc->GetLoadedEntity)
		{
			auto& allRes = *gameFunc->GetLoadedEntity(gameFunc->entityRes);
			for (auto& p : allRes)
			{
				if (p.first->layerType == 0)
				{
					mainEntityLayer = &p.second;
					break;
				}
			}
		}
		//寻找核心车站
		auto wcoreStation = coreStation.lock();
		if (lr != 0 && !wcoreStation)
		{
			EntityLayer* layer = (EntityLayer*)entityLayer;
			for (auto& p : layer->Ls)
			{
				if (p->lr != 0)
					continue;
				if (p->el.name == AISTATION_CREATENAME)
				{
					auto e = std::static_pointer_cast<AiStation> (p);
					if (e->stationID == stationID)
					{
						coreStation = e;
						break;
					}
				}
			}
		}
	}
	if (lr == 0)
	{
		//绘制连线，往上连线
		if (stationID.front() == 0 && stationID.size() == 1)//根不用连
		{
			ani.sprite_index = lr == 0 ? L"ai_station_root" : L"ai_station_extend";
		}
		auto wupperEntity = upperEntity.lock();
		if (wupperEntity)
		{
			DWORD c = RGBA(0xff, 0, 0, 0xff);
			AddLine(lineList, 0, 0, 0, c, wupperEntity->x - x, wupperEntity->y - y, c);
		}
	}
}

std::shared_ptr<Entity> CreateAiStation()
{
	return std::make_shared<AiStation>();
}
