#include <iostream>
#include <conio.h>
#include <time.h>
using namespace std;

#include "board.h"


int main()
{
	char choice=NULL;
	bool showProgress=false;

	// (with the use of Warnsdorff's algorithm, the process is too fast to see anyway so showProgress is useless)
	//cout << "\nTurn on progress display (will dramatically slow down my thinking): ";
	//if ( toupper(_getch()) == 'Y' ) showProgress=true;

	do {
		int size=0;
		bool solved=false;

		do {
			cout << "\nEnter board rows (or columns): ";
			cin >> size;
			if ( size < 1 ) { cout << "What are you, crazy?!\n"; }
		} while ( size < 1 );

		// create the board
		gameBoard theBoard(size);
		// let the user select the initial starting position
		theBoard.setInitialPosition();
		position startPos=theBoard.getKnightPosition();
		// show the initial board while I think about the solution
		theBoard.displayBoard();

		cout << "Thinking...";

		clock_t t1=clock(); // start a stopwatch
		if ( theBoard.solve(startPos,0,showProgress) )
		{
			theBoard.displayBoard();
			cout << "Behold!  The solution!\n";
			solved=true;
		} else
		{
			cout << "\nI couldn't find a solution, should I try to brute force it?: ";
			choice=toupper(_getch());
			if ( choice=='Y' )
			{	cout << "\nThinking Harder...";
				t1=clock();	// restart the clock
				if ( theBoard.solve(startPos,0,showProgress,true) )
				{
					theBoard.displayBoard();
					cout << "Behold!  The solution! (Brute forced)\n";
					solved=true;
				}
			}
		}

		clock_t t2=clock(); // how long did it take?
		double solveTime=double((t2-t1)/1000.0);

		if ( !solved )
		{
			theBoard.displayBoard();
			cout << "No solution was found\n";
			solved=false;
		}

		do {
			theBoard.displayBoard();
			if ( solved ) cout << "Behold!  The solution!\n";
			cout << "Run time: " << solveTime << " seconds.\n";
			if ( solved ) 
				cout << "[S]tep through, ";
			cout << "[T]ry another, [E]xport text file, [Q]uit: ";
			choice=toupper(_getch());
			cout << endl;

			if ( solved && choice == 'S' )
				theBoard.stepThroughSolution();	
			else if ( choice == 'E' )
			{
				char filename[80]={NULL};
				fflush(stdin);
				cout << "Enter filename: ";
				cin.getline(filename,80);
				theBoard.saveToFile(filename,solveTime);
			}
		} while ( choice != 'T' && choice != 'Q' );

	} while ( choice == 'T' );
	

	return 0;
};

void setScreenPos(position pos)
{
	COORD coord;
	coord.X=short( (pos.x*4)+1 );
	coord.Y=short( (pos.y*2)+1 );
	SetConsoleCursorPosition ( GetStdHandle(STD_OUTPUT_HANDLE), coord);
}