/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/domains/graphics/color/colornames.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/core/sgxlib/sgxlib.hpp"
#include "domains/graphics/color/colortypes.hpp"


tBOOL
sgxColorRGBA::fromName(sgxColorRGBA &col, const sgxString &str) {
	return fromName(col, str.c_str());
}

tBOOL
sgxColorRGB::fromName(sgxColorRGB &col, const sgxString &str) {
	sgxColorRGBA intcol;
	tBOOL rt = sgxColorRGBA::fromName(intcol, str.c_str());
	col = intcol.rgb();
	return rt;
}

tBOOL
sgxColorRGB::fromName(sgxColorRGB &col, const char *pName) {
	sgxColorRGBA intcol;
	tBOOL rt = sgxColorRGBA::fromName(intcol, pName);
	col = intcol.rgb();
	return rt;
}

void	
sgxColorRGB::fromInt(const tUINT32 col) {
	r = ((col >> 16)&255) / 255.0f;
	g = ((col >> 8)&255)  / 255.0f;
	b = ((col >> 0)&255)  / 255.0f;
}

void	
sgxColorRGBA::fromInt(const tUINT32 col) {
	r = ((col >> 24)&255) / 255.0f;
	g = ((col >> 16)&255) / 255.0f;
	b = ((col >> 8)&255)  / 255.0f;
	a = ((col >> 0)&255)  / 255.0f;
}

//
// Real handler
//
tBOOL
sgxColorRGBA::fromName(sgxColorRGBA &col, const char *pName) {
	static struct { const char *pColName; sgxColorRGBA colRGB; } colourList[] = {
		{ "White",	sgxColorRGBA::White, },
		{ "LtGrey", sgxColorRGBA::LtGrey, },
		{ "DkGrey", sgxColorRGBA::DkGrey, },
		{ "Black",	sgxColorRGBA::Black, },
		{ "Red",	sgxColorRGBA::Red, },
		{ "Green",	sgxColorRGBA::Green, },
		{ "Blue",	sgxColorRGBA::Blue, },
	};

	for(int i=0;i<sizeof(colourList)/sizeof(colourList[0]);++i) {
		if (sgxStricmp(colourList[i].pColName, pName) == 0) {
			col = colourList[i].colRGB;
			return TRUE;
		}
	}

	return FALSE;
}

static tUINT32 xtoi(char a, char b) {
	tUINT32 d1 = 0;

	if (a >= '0' && a <= '9') {
		d1 |= (a-'0') * 16;
	} else if (a >= 'a' && a <= 'f') {
		d1 |= ((a-'a') + 10) * 16;
	}
	//
	if (b >= '0' && b <= '9') {
		d1 |= b-'0';
	} else if (b >= 'a' && b <= 'f') {
		d1 |= (b-'a') + 10;
	}
	//
	return d1;
}

sgxColorRGBA	
sgxColorRGBA::fromHexString(const char *pHexString) {
sgxColorRGBA col;

	col.r = xtoi(pHexString[0], pHexString[1]) / 255.0f;
	col.g = xtoi(pHexString[2], pHexString[3]) / 255.0f;
	col.b = xtoi(pHexString[4], pHexString[5]) / 255.0f;
	if (sgxStrlen(pHexString) > 6) {
		col.a = xtoi(pHexString[6], pHexString[7]) / 255.0f;
	} else {
		col.a = 1;
	}
	return col;
}

