
#include <windows.h>
#include <gl/gl.h>

#include "fWord.h"

namespace fingers
{

	fWord::fWord()
	{
		active = false;
	}

	void fWord::finish()
	{
		for ( int i = current; i < length; i++ )
			buffer[i] = '0';

	}

	int fWord::getErrors()
	{
		int errors = 0;

		for ( int i = 0; i < current; i++ )
		{
			if ( word[i] != buffer[i] )
				errors++;
		}

		return errors;
	}

	int fWord::getLenght()
	{
		return strlen(word) * 11;
	}

	int fWord::getScore()
	{
		int score = 0;

		for ( int i = 0; i < length; i++ )
		{
			if ( word[i] == buffer[i] && buffer[i] != NULL )
				score += 10;

			else if ( word[i] != buffer[i] && buffer[i] != NULL )
				score -= 7;

			else
				score -= 5;
		}

		return score * length - backcount * 10;
	}

	int fWord::getStrLenght()
	{
		return strlen(buffer);
	}

	void fWord::input(int key)
	{
		if ( current < length )
		{
			if ( key >= 'A' && key <= 'Z' )
			{
				if ( GetAsyncKeyState(VK_SHIFT) )
					buffer[current++] = key;
				else
					buffer[current++] = key + 32;
			}
		}

		if ( key == VK_BACK )
		{
			if ( current > 0 )
			{
				buffer[--current] = NULL;
				backcount++;
			}
		}
	}

	void fWord::render(text_c& text, bool current)
	{
		if ( active )
		{
			glColor3f(0.0f, 0.0f, 0.0f);
			text.printf(x+1, y+1, "%s", word);

			for ( int i = 0; i < length; i++ )
			{
				if ( word[i] == buffer[i] && buffer[i] != NULL )
					glColor3f(0.2f, 0.8f, 0.2f);

				else if ( word[i] != buffer[i] && buffer[i] != NULL )
					glColor3f(1.0f, 0.0f, 0.0f);

				else
				{
					if ( current )
						glColor3f(1.0f, 1.0f, 0.0f);
					else
						glColor3f(1.0f, 1.0f, 1.0f);
				}

				text.printf(x + i*11, y, "%c", word[i]);
			}
		}
	}

	void fWord::update(float amount)
	{
		if ( active )
		{
			x -= amount * 100;

			/*if ( x <= -getLenght() )
			{
				active = false;
			}*/
		}
	}

	void fWord::spawn(const char* word)
	{
		memset(this->word, 0, 32);
		strcpy_s(this->word, 32, word);
		x = 825.0f;
		y = 75 + 450 * (rand() / (RAND_MAX + 1.0f));

		active = true;
		current	= 0;
		backcount = 0;
		length	= strlen(word);

		memset(buffer, 0, 32);
	}

}