#include "../includes.h"
#include "scene.h"
#include "../parse/scene_parser.h"
#include "scene_elements.h"

Scene::Scene(const char* path) {
	//printf("Creating parser.\n");
	parser = new SceneParser(this,path);

	camera = new Camera();
	image = new Image();
	materials = new map<string,Material*>();
	objects = new list<Object*>();
	lights = new map<string,Light*>();
	loaded_objects = new list<glLib::Object::object*>();

	Light::init();

	//Parse scene
	valid = true;
	error_trace = parser->parse();
	if (error_trace!=NULL) valid = false;

	//Setup objects
	for (list<Object*>::const_iterator iter=objects->begin(); iter!=objects->end(); ++iter) {
		(*iter)->init();
	}

	for (map<string,Material*>::const_iterator iter=materials->begin();iter!=materials->end();++iter) {
		iter->second->init();
	}
}
Scene::~Scene() {
	if (error_trace!=NULL) {
		for (list<string*>::iterator iter=error_trace->begin(); iter!=error_trace->end(); ++iter) {
			delete *iter;
		}
		delete error_trace;
	}

	delete parser;

	delete camera;
	delete image;

	while (materials->size()>0) {
		Material* material = materials->begin()->second;
		/*//Objects delete their own textures.  So don't do it for them.
		if (!string_startswith("__",*material->name)) {
			//printf("Deleting material %s.\n",material->name->c_str());
			delete material;
		}
		//else printf("NOT deleting material %s.\n",material->name->c_str());*/
		delete material;
		materials->erase(materials->begin());
	}
	delete materials;

	while (objects->size()>0) {
		delete objects->front();
		objects->pop_front();
	}
	delete objects;

	while (loaded_objects->size()>0) {
		delete loaded_objects->front();
		loaded_objects->pop_front();
	}
	delete loaded_objects;

	while (lights->size()>0) {
		delete lights->begin()->second;
		lights->erase(lights->begin());
	}
	delete lights;
}

void Scene::print_error(int padding) {
	if (error_trace!=NULL) {
		for (list<string*>::const_iterator iter=error_trace->begin(); iter!=error_trace->end(); ++iter) {
			for (int i=0;i<padding;++i) printf(" ");
			printf("%s\n",(*iter)->c_str());
		}
	}
	else {
		printf("No error message!\n");
	}
}