#include "libgg/cMain.h"
#include "libgg/Geometry.h"
#include "libcc/efolder.h"
#include "libmap/cMapWriter.h"

#pragma comment(lib, "library/libz")
#ifdef max
#undef max
#endif // max

#ifdef min
#undef min
#endif // min


static std::string pathScene = "scene/";
static std::vector<int> s_ids;
static int s_index = -1, s_w = GetSystemMetrics(SM_CXSCREEN) - 32, s_h = GetSystemMetrics(SM_CYSCREEN) - 96;
static cNode* scene = nullptr;
static cLabel* labelDesc = nullptr, *labelMapid = nullptr;
static cMapWriter* currWriter = nullptr;


static void onCreateMap(cNode* node, cLabel* labelMapid, cLabel* labelDesc)
{
	if (++s_index >= s_ids.size())
	{
		return;
	}
	currWriter = cMapWriter::create(pathScene, s_ids[s_index], labelMapid, labelDesc);
	if (currWriter == nullptr)
	{
		return;
	}	
	Size size = currWriter->getContentSize();
	float sc = std::min(s_w / size.width, s_h / size.height);
	sc = std::min(sc, 1.0f);
	currWriter->setScale(sc);
	node->addChild(currWriter);
}

class cRootNode : public cNode
{
public:
	CREATE_FUNC(cRootNode);

	void update(float delta)
	{
		if (currWriter == nullptr)
		{
			return;
		}
		if (currWriter->_isFinish)
		{
			currWriter->unscheduleUpdate();
			currWriter->removeFromParent();
			onCreateMap(scene, labelMapid, labelDesc);
		}
	}
};

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	cMain m;
	scene = cRootNode::create();
	cNode::setRoot(scene);
	if (!m.init(s_w, s_h))
	{
		return 0;
	}
	gg::setTitle("������.��ͼ");

	auto floders = cc::efolder(pathScene, true, 0);
	for (auto name : floders)
	{
		int len = name.size();
		if (len == 8 && name[len - 4] == '.' && name[len - 3] == 'm' && name[len - 2] == 'a' && name[len - 1] == 'p')
		{
			name = name.substr(0, 4);
			s_ids.push_back(std::atoi(name.c_str()));
		}
	}

	labelDesc = cLabel::create();
	labelDesc->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
	labelDesc->setPosition(s_w / 2, 0);
	scene->addChild(labelDesc, 1);


	labelMapid = cLabel::create("");
	labelMapid->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
	labelMapid->setPosition(s_w / 2, 20);
	scene->addChild(labelMapid, 1);

	if (s_ids.empty())
	{
		labelMapid->setString("δ�ҵ���ʶ���scene/*.map�ļ�");
	}

	onCreateMap(scene, labelMapid, labelDesc);
	if (!s_ids.empty())
	{
		scene->scheduleUpdate();
	}
	m.start();
 	return 0;
}