#include "Application.h"
#include "Utilities/Log.h"

#include "physfs.h"

using namespace BlueCore;

void initializePhysfs(char* program)
{
	// setup physfs
	PHYSFS_init(program);

	std::string appdir = PHYSFS_getUserDir();
	appdir += ".bluecore";

	if ( !PHYSFS_setWriteDir(appdir.c_str()) )
	{
		if ( (PHYSFS_setWriteDir(PHYSFS_getUserDir()))
				&& (PHYSFS_mkdir(".bluecore")))
			PHYSFS_setWriteDir(appdir.c_str() );
	}

	PHYSFS_addToSearchPath(appdir.c_str(), 0);
	PHYSFS_addToSearchPath("data", 1);

	char **rc = PHYSFS_enumerateFiles("");

	for (char **i = rc; *i != 0; i++)
	{
		std::string filename( *i);

		if (filename.substr(filename.size() - 4, 4) == ".zip")
		{
			PHYSFS_addToSearchPath(( "data/" + filename ).c_str(), 1);
			clog << ">>> Using addon: "<< filename << endlog;
		}
	}

	PHYSFS_freeList(rc);
}

void shutdownPhysfs()
{
	PHYSFS_deinit();
}

int main(int argc, char **argv)
{
	initializePhysfs(argv[0]);

	ref_ptr<Application> app = new Application();

	if (app->initialize())
	{
		app->run();
	}
	app->shutdown();

	shutdownPhysfs();
}
