/*
 * LoadSave.cpp
 *
 *  Created on: 2009-07-10
 *      Author: wasyl
 */

#include <cstdio>
#include "../prep/Common.h"
#include "../prep/ent/Entity.h"
#include "../thing/Tile.h"
#include "../thing/Avatar.h"
#include "../thing/Bag.h"
#include "../thing/Container.h"
#include "../thing/Message.h"
#include "../thing/Garbage.h"
#include "../thing/Lever.h"
#include "../thing/Spikes.h"
#include "../thing/ForceField.h"
#include "../thing/PressPad.h"
#include "../thing/Baddie.h"
#include "../thing/Fireworks.h"
#include "LoadSave.h"

LoadSave::LoadSave()
{
	mapping["tl"] = new Tile(0,NULL,0,0);
	mapping["ct"] = new Container(Vec(0,0),1);
	mapping["gb"] = new Bag();
	mapping["av"] = new Avatar();
	mapping["ms"] = new Message("");
	mapping["lg"] = new Garbage();
	mapping["vr"] = new Lever(0, 0);
	mapping["sp"] = new Spikes();
	mapping["ff"] = new ForceField(true);
	mapping["pr"] = new PressPad(0,0);
	mapping["bd"] = new Baddie(false);
	mapping["fw"] = new Fireworks();
}

LoadSave::~LoadSave()
{
	std::map<std::string,Entity*>::iterator it;
	for (it = mapping.begin(); it != mapping.end(); it++)
		delete (*it).second;
}


void LoadSave::load(const char *filename, World *world)
{
	FILE *f = fopen(filename, "rb");
	if (!f)
	{
		std::printf("CANNOT OPEN '%s'!!!\n", filename);
		std::exit(1);
	}

	char buf[3] = "  ";
	while (!feof(f))
	{
		buf[0] = (char)fgetc(f);
		buf[1] = (char)fgetc(f);
		if (buf[0] == -1 || buf[1] == -1)
			break;

		Entity *ld = mapping[buf];
		if (!ld)
		{
			std::printf("UNMAPPABLE '%s'!!!\n", buf);
			std::exit(1);
		}
		ld = ld->clone();
		ld->load(f);
		world->add(ld);
	}

	fclose(f);
}

void LoadSave::save(const char *filename, World *world)
{
	FILE *f = fopen(filename, "wb");
	if (!f)
	{
		std::printf("CANNOT OPEN '%s'!!!\n", filename);
		std::exit(1);
	}

	Entities &ents = world->index(ID("entt"));
	FOREACH(vector,Entity*,e,ents)
	{
		(*e)->save(f);
	}

	fclose(f);
}
