#include "state.h"
#include <malloc.h>

int State::size = 19;

State::State( void )
{
	board = (type*)malloc(sizeof(type) * size * size);
}

State State::generateState (SDL_Surface *boardImg, Settings settings)
{
	State state;
	int i, j, x, y, r, sum;
	point p;
	r = 20;
	for (i = 0; i < size; i++) {
		for (j = 0; j < size; j++) {
			p = positionPoint(i, j, settings);
			for (y = p.y-r; y < p.y+r; y++) {
				for (x = p.x-r; x < p.x+r; x++) {
					uint32_t px = PX(boardImg, x, y);
					sum += PXR(px) + PXG(px) + PXB(px);
				}
			}
			type t = BOARD;
			if (sum < settings.getBlackTreshold()) t = BLACK;
			if (sum > settings.getWhiteTreshold()) t = WHITE;
			PX_(state.board, i, j, size, size) = t;
		}
	}
	return state;
}

point State::positionPoint(int i, int j, Settings s)
{
	point ul = s.getUL(), ur = s.getUR(), bl = s.getBL(), br = s.getBR();
	point topp, botp, pp;
	topp.x = ul.x + (i*(ur.x-ul.x))/size;
	topp.y = ul.y + (i*(ur.y-ul.y))/size;
	botp.x = bl.x + (i*(br.x-bl.x))/size;
	botp.y = bl.y + (i*(br.y-bl.y))/size;
	pp.x = topp.x + (j*(botp.x-topp.x))/size;
	pp.y = topp.y + (j*(botp.y-topp.y))/size;
	return pp;
}