#include "stdafx.h"
#include "ObjMaterialReader.h"
#include "IOUtility.h"

using namespace std;


namespace lib_geo
{


ObjMaterialReader::ObjMaterialReader(const std::string& workdir) :
	m_LoadWorkDirPath(workdir)
{
}

bool ObjMaterialReader::ReadMaterialFile( const string& filename , ObjMaterialGroup& materials )
{
	string full_name = m_LoadWorkDirPath + filename;

	ifstream ifs( full_name.c_str() );
	if( !ifs.is_open() )
		return false;

	string s;

	materials.m_Filename = filename;

	for(;;)
	{
		if( ifs.eof() )
			break;

		ifs >> s;
		if( s.empty() )
			continue;

		if( s == "newmtl" )
		{
			ObjMaterial new_mat;
			GetLineWithTrimed( ifs , new_mat.m_Name );
			new_mat.m_FileDirPath = m_LoadWorkDirPath;

			materials.m_Materials.push_back( new_mat );
		}
		else
		{
			if( materials.m_Materials.empty() )
			{
				ReadToNextLine( ifs );
				continue;
			}

			ObjMaterial& last_mat = materials.m_Materials.back();
			if( s == "Ns" )
			{
				ifs >> last_mat.m_Shininess;
			}
			else if( s == "Ka" )
			{
				ifs >> last_mat.m_Ambient.x >> last_mat.m_Ambient.y >> last_mat.m_Ambient.z;
			}
			else if( s == "Kd" )
			{
				ifs >> last_mat.m_Diffuse.x >> last_mat.m_Diffuse.y >> last_mat.m_Diffuse.z;
			}
			else if( s == "Ks" )
			{
				ifs >> last_mat.m_Specular.x >> last_mat.m_Specular.y >> last_mat.m_Specular.z;
			}
			else if( s == "Ni" )
			{
				ifs >> last_mat.m_Ni;
			}
			else if( s == "illum" )
			{
				ifs >> last_mat.m_Illum;
			}
			else if( s == "map_Kd" )
			{
				GetLineWithTrimed(ifs, last_mat.m_TextureFileName);
			}
			else if( s == "map_Bump" )
			{
				GetLineWithTrimed(ifs, last_mat.m_NormalMapFileName);
			}
			else if( s == "d" )
			{
				ifs >> last_mat.m_Transparent;
			}
			else if( s == "Tr" )
			{
				ifs >> last_mat.m_Transparent;
			}
			else
			{
				ReadToNextLine( ifs );
			}
		}
	}

	return true;
}


}
