/*
 * $Id: ioobj.cpp,v 1.15 2008-06-06 20:02:36 kybav1 Exp $
 *
 * Description  : One line description of file.
 * Author       : Antonin Misek <antonin.misek@skoda-auto.cz>
 *
 * Purpose      :
 *     Long description of what the file is for.
 */


//#include <wx/stopwatch.h>
#include "ioobj.h"
#include "objparser.h"
#include "mtlparser.h"
#include "objwriter.h"

using namespace VRUT;


IOObj::IOObj(const MODULE_ID & _id, const wxString & _name, Kernel * _kernel) : IOModule(_id, _name, 0, _kernel), optimize(true)
{
	REGISTER_PARAM_GUI_CHECKBOX(optimizeParamID, wxT("optimize"), optimize, wxT("optimize geometries during import"));
}


IOObj::~IOObj()
{
}


wxString IOObj::GetDesc() const
{
	return wxT("Import and export OBJ files");
}


wxString IOObj::GetSupportedExts() const
{
	return wxT("OBJ");
}


void IOObj::processEvent(Event * evt)
{
	IOModule::processEvent(evt);
	switch (evt->type)
	{
	case Event::EVT_PARAM_SET:
	{
		UPDATE_PARAM_FROM_EVENT_BOOL(optimizeParamID, optimize, evt);
		break;
	}
	default:
		break;
	}
}


bool IOObj::ImportScene(const wxString &fname, SCENE_ID _sceneID, const NODE_ID &rootID)
{
	IOObjImportJob *job=new IOObjImportJob(fname, _sceneID, rootID, this, optimize);
	KERNEL->GetMessageSink()->ProcessJob(job);
	return true;
}


bool IOObj::ExportScene(smart_pointer_v2<Scene> &scene, const NODE_ID rootID, const wxString &fname)
{
	wxFileOutputStream sceneStream(fname);
	if (sceneStream.IsOk())
	{
		wxBufferedOutputStream sceneStream2(sceneStream, 1000000);
		OBJWriter objWriter(&sceneStream2, scene.getPtr());
		objWriter.Write(rootID);
		sceneStream2.Sync();
		return true;
	}
	return false;
}


void IOObj::IOObjImportJob::Run()
{
	wxStopWatch sw;
	wxInputStream * is = GetInputStream(fname);
	if (is)
	{
		OBJParser objParser(is, sceneID, fname, module);
		objParser.Parse(rootID, optimize);

		if(objParser.isMatLib()) 
		{
			wxFileName objPath(fname);
			wxFileName mtlPath(objParser.getMatLibName());
			objPath.SetFullName(mtlPath.GetFullName());
			mtlPath = objPath;
			wxInputStream * mtl_is = GetInputStream(mtlPath.GetFullPath());
			if (mtl_is)
			{
				MTLParser mtlParser(mtl_is, sceneID, mtlPath.GetFullPath(), module);
				mtlParser.Parse(rootID);
				delete mtl_is;
			}
		}
		delete is;
	}
	LOG(wxString::Format(wxT("<IOObj>Scene parsed in %.3f secs, ID %lu, "), 0.001f * sw.Time(), (unsigned long)sceneID) + fname);
	module->PostToKernel(GET_EVT_IO_SCENE_IMPORT_DONE(sceneID, rootID, fname));
}

EXPORT_VRUT_BASE_MODULE_FUNCTIONS( IOObj )
