#include "material.h"
#pragma warning(push)
#pragma warning(disable:4996)
#include <strstream>

using namespace std;
using namespace kLibrary::factory;

namespace CBK
{
	unsigned long Material::numMaterialChanges;
	Material* Material::currentMaterial = 0;

	Material::Material(const string& name, IDirect3DDevice9* device) : Object(device)
	{
		material = 0;

		load(name);
	}

	Material::~Material(void)
	{
		d3d::Delete<D3DMATERIAL9*>(material);
	}

	Object& Material::reset(void)
	{
		return *this;
	}

	Material& Material::load(const string& name)
	{
		if (material != 0)
		{
			delete material;
		}

		material = new D3DMATERIAL9();
		
		if (name == "")
		{
			delete material;
			material = 0;
			setName(name);
			return *this;
		}
		else
		{
			char* temp = new char[name.size() + 1];
			name.copy(temp, name.size());
			temp[name.size()] = '\0';
			strstream myBuff(temp, streamsize(name.size()));

			myBuff >> material->Ambient.r;
			myBuff >> material->Ambient.g;
			myBuff >> material->Ambient.b;
			myBuff >> material->Ambient.a;

			myBuff >> material->Diffuse.r;
			myBuff >> material->Diffuse.g;
			myBuff >> material->Diffuse.b;
			myBuff >> material->Diffuse.a;

			myBuff >> material->Specular.r;
			myBuff >> material->Specular.g;
			myBuff >> material->Specular.b;
			myBuff >> material->Specular.a;

			myBuff >> material->Emissive.r;
			myBuff >> material->Emissive.g;
			myBuff >> material->Emissive.b;
			myBuff >> material->Emissive.a;

			myBuff >> material->Power;

			delete [] temp;
		}

		setName(name);
		return *this;
	}

	void Material::apply(void)
	{
		if (device == 0) return;

		if (currentMaterial != this)
		{
			device->SetMaterial(material);
			currentMaterial = this;
			numMaterialChanges++;
		}
	}

	void Material::clear(IDirect3DDevice9* device)
	{
		if (device == 0) return;

		if (currentMaterial != 0)
		{
			Material("1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 20").apply();
			currentMaterial = 0;
			numMaterialChanges++;
		}
	}
}

#pragma warning(pop)