#include "q2048ai.h"

#include "q2048view.h"
#include "q2048tile.h"

#include <QDebug>

Q2048AI::Q2048AI(Q2048View* v) : View(v)
{
}

int Q2048AI::move(int lastmove)
{
	int fill_row = 0;

	for (int row = 0; row < View->Size; row++)
	{
		for (int col = 0; col < View->Size; col++)
		{
			Q2048Tile* t = Q2048Tile::getTile(col, row);
			if (t==0)
			{
				fill_row = row+1;
				qDebug() << "fillrow" << fill_row;
				break;
			}
		}

		if (fill_row)
		{
			fill_row--;
			break;
		}
	}



	if ( (lastmove == Qt::Key_Left) && (fill_row==0) )
		return Qt::Key_Right;

//	if (fill_row == 0)
//		return Qt::Key_Up;

	//merge up?
	for (int col = 0; col < View->Size; col++)
	{
		int lastval=0;
		for (int row = 0; row < View->Size; row++)
		{
			Q2048Tile* t = Q2048Tile::getTile(col, row);
			if (t)
			{
				if (t->value()==lastval) //ok - merge up
					return Qt::Key_Up;

				lastval = t->value();
			}
		}
	}


	//merge left/right?
	for (int row = 0; row < View->Size; row++)
	{
		int lastval=0;
		for (int col = 0; col < View->Size; col++)
		{
			Q2048Tile* t = Q2048Tile::getTile(col, row);
			if (t)
			{
				if (t->value()==lastval) //ok - merge up
					return (fill_row==0)? Qt::Key_Right : Qt::Key_Left;

				lastval = t->value();
			}
		}
	}


	if (lastmove == Qt::Key_Left)
		return Qt::Key_Right;
	else
		return Qt::Key_Left;

	//return humanmove;
}
