#include "Drawbox.h"
#include "Rect.h"
#include "GraphicUtil.h"
#include "apmatrix.h"

const int maxsize = 20;

int size = 3;
int minsquare = 2;  // protector against infinite recursion
apmatrix <int> squares(maxsize, maxsize);
Rect board;

void SetupScreen() {
	int k=min(screenRect.width(), screenRect.height()) - 40;
	Point c=screenRect.center();
	board.left = 	c.x - k/2;
	board.right = 	c.x + k/2;
	board.top = 	c.y - k/2;
	board.bottom = 	c.y + k/2;
}

void Menu() {
	SetFont(12);
	SetColor(gray);
	DrawText(350, screenRect.top+14, "s: set size     r:  reset       q: quit");
}

void SetupSquares() {
	int a=0, b=0;
	for (int i=0; i<size; i++) {
		b = a;
		for (int j=0; j<size; j++) {
			squares[i][j] = b;
			b = 1-b;
		}
		a = 1-a;
	}
}

void Draw(Rect &r) {
	Rect sq;
	for (int i=0; i<size; i++) {
		for (int j=0; j<size; j++) {
			sq = r.subRect(size, size, i, j);
			int color = squares[i][j];
			if (color==0) Rectangle(sq, filled+blue);
			else if (color==1) Rectangle(sq, filled+yellow);
			else if (size > 1 && sq.width() >= minsquare) // protections against infinite recursion
				Draw(sq);
			else Rectangle(sq, filled+green);  // recursion stopper - final state
		}
	}
}

void ClickSquare(int row, int col) {
	squares[row][col] = (squares[row][col] + 1) % 3;
	Rect sq = board.subRect(size, size, row, col);
	Rectangle(sq, filled+gray);  // short term, until Draw gets there
	Draw(board);
}

void Clicked(Point p) {
	int row, col;
	if (board.contains(p)) {
		board.whichSubRect(size, size, p, row, col);
		ClickSquare(row, col);
	}
	else ; // sassy remark later
}

void SetSize() {
	SetColor(60);
	SetFont(18);
	size = InputInt(100, 35, "How many across? ");
	if (size > maxsize) {
		SetColor(1);
		DrawText("    Sorry, the maximum is ");  DrawNum(maxsize);
		size = maxsize;
		Sleep(500);
	}
	minsquare = max(size/2, 2);
	DrawBackground();
}

void Main() {
	SetupScreen();
	SetupSquares();
	Draw(board);
	Menu();
	
	while (true) {
		char k;
		Point p;
		if (GetKey(k)) {
			switch (k) {
				case 's':  // set size
					SetSize(); 
					SetupSquares(); 
					Draw(board);
					Menu();
					break;
				case 'r':  // reset
					SetupSquares(); 
					Draw(board);
					break;
				case 'q':  Quit();  // no break needed, this is a breaking-out event anyway
			}
		}
		else if (GetClick(p)) {
			Clicked(p);
		}
	}
}


