#include "Output.h"
#include <Windows.h>
#include <iostream>
#include <sstream>

using namespace std;

void Output::Text(string aString)
{	
	if (mSaveLoading)
		return;

	//Breaks up your words and makes sure you wrap full words
	unsigned int bufferWidth = GetBufferWidth();

	for (unsigned int i = 1; i <= aString.length(); ++i)
	{
		char c = aString[i-1];

		int spaceCount = 0;

		//Couldn't figure out how to get it to work with the \n, I found this on a tutorial site.
		if (c == '\n')
		{
			int charNumOnLine = ((i) % bufferWidth);
			spaceCount = bufferWidth - charNumOnLine;
			aString.insert((i-1), (spaceCount), ' ');
			i += (spaceCount);
			continue;
		}

		if ((i % bufferWidth) == 0)
		{
			int spaceCount = 0;

			if (aString[(i-1)] != ' ')
			{
				for (int j = (i-1); j > -1; --j)
				{
					if (aString[j] == ' ')
					{
							aString.insert(j, spaceCount, ' ');
							break;						
					}
					else spaceCount++;
				}
			}
		}
	}

	// Output string to console
	cout << aString;
}

void Output::TextQuote(std::string aString)
{
	if (mSaveLoading)
		return;

	string str = ("\"" + aString + "\"");
	Text(str);
}

void Output::Int(int aInt)
{
	if (mSaveLoading)
		return;

	string result;

	stringstream stream;
	stream << aInt;
	result = stream.str();

	Text(result);
}

void Output::Char(char aChar)
{
	if (mSaveLoading)
		return;

	cout << aChar;
}

void Output::EndLines(int aLines)
{
	if (mSaveLoading)
		return;

	while(aLines--)
		cout << endl;
}

void Output::ClearScreen()
{
	if (!mClearScreen)
		return;

	system("cls");
}

int Output::GetBufferWidth()
{
	//Gets the width of the console screen, so you test word wrap
	CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
	int bufferWidth, result;

	result = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&bufferInfo);

	if(result)
	{
		bufferWidth = bufferInfo.dwSize.X;
	}

	return bufferWidth;
}

void Output::Disable(bool aClearScreen) 
{ 
	if (aClearScreen)
		mClearScreen = false;

	mSaveLoading = true; 
}

void Output::Enable(bool aClearScreen)
{ 
	if (aClearScreen)
		mClearScreen = true;

	mSaveLoading = false; 
}