#include "cardinfo.h"

// This function returns true if the extension is there.
bool CARDINFO::isExtensionSupported(string extstring)
{
	char * temp = (char *) glGetString(GL_EXTENSIONS);
	if (temp == 0)
	{
		cout << "Error getting extensions.  Continuing anyway, errors may follow!" << endl;
		return true;
	}

	string s = temp;
	string::size_type temppos = s.find(extstring);

	bool hasext = (temppos <= s.length());

	if (!hasext)
	{
		cout << "Extension not supported: " << extstring << endl;
	}

	//cout << s << endl;

	return hasext;
}

void CARDINFO::ResetDB()
{
	db.resize(NUM_CARDINFOTYPES);
	dbvalid = false;
}

int CARDINFO::GetCapability(CARDINFOTYPE::TYPE capability)
{
	if (!dbvalid)
		return -1;
	
	if (capability >= 0 && capability < NUM_CARDINFOTYPES)
	{
		return db[capability].data;
	}
	
	return -1;
}

void CARDINFO::BuildCardInfo()
{
	if (isExtensionSupported( "GL_ARB_multitexture" ))
	{
		db[CARDINFOTYPE::MULTITEXTURE].data = 1;
		GLint tu;
		glGetIntegerv( GL_MAX_TEXTURE_UNITS_ARB,&tu );
		db[CARDINFOTYPE::TEXTUREUNITS].data = tu;
	}
	else
	{
		db[CARDINFOTYPE::MULTITEXTURE].data = 0;
		db[CARDINFOTYPE::TEXTUREUNITS].data = 1;
	}
	
	if (isExtensionSupported( "GL_EXT_texture_filter_anisotropic" ))
	{
		db[CARDINFOTYPE::ANISOTROPY].data = 1;
		GLint aniso;
		glGetIntegerv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,&aniso );
		db[CARDINFOTYPE::MAXANISOTROPY].data = aniso;
	}
	else
	{
		db[CARDINFOTYPE::ANISOTROPY].data = 0;
		db[CARDINFOTYPE::MAXANISOTROPY].data = -1;
	}
	
	dbvalid = true;
}

void CARDINFO::PrintCardInfo(ostream & out)
{
	if (dbvalid)
	{
		out << "Multitexture: ";
		if (db[CARDINFOTYPE::MULTITEXTURE].data == 1)
			out << "Yes" << endl;
		else
			out << "No" << endl;
		out << "Texture units: " << db[CARDINFOTYPE::TEXTUREUNITS].data << endl;
		out << "Anisotropic texture filtering: ";
		if (db[CARDINFOTYPE::ANISOTROPY].data == 1)
		{
			out << "Yes" << endl;
			out << "Maximum Anisotropy: " << db[CARDINFOTYPE::MAXANISOTROPY].data << endl;
		}
		else
			out << "No" << endl;
	}
	else
		cout << "Card info not yet built" << endl;
}
