import objectdraw.*;

public class MagicSquare {
	// size of cell inside each slot of magic square
	private static final int DIGIT_WIDTH = 10; 
	private static final int GAP = 3; 

	// buffer space between lines and #s in magic square
	private static final int OFFSET = 3;  

	// Array holding entries in magic square and its size
	private int [][] magicArray;
	
	public MagicSquare(Location point, int size, DrawingCanvas canvas){
		magicArray = new int[size][size];
		fillSquare(size);
		displaySquare(point, size, canvas);
	}

	// Place values to make a magic square
	private void fillSquare(int size) {

		// Initialize to all 0s
		for (int row = 0; row < size; row++) {
			for (int col = 0; col < size; col++) {
				magicArray[row][col] = 0;
			}
		}

		// Set the indices for the middle of the bottom row
		int currRow = size - 1;
		int currCol = size / 2;

		// Fill each cell
		for (int nextInt = 1; nextInt <= size * size; nextInt++) {
			magicArray[currRow][currCol] = nextInt;

			// Find the next cell, wrapping around if necessary
			int nextRow = (currRow + 1) % size;
			int nextCol = (currCol + 1) % size;

			// If the cell is empty, remember those indices for the
			// next assignment
			if (magicArray[nextRow][nextCol] == 0) {
				currRow = nextRow;
				currCol = nextCol;
			} else {
				// The cell was full - Use the cell above the previous one
				currRow = (currRow - 1 + size) % size;
			}
		}
	}

	// draws the square on the canvas
	private void displaySquare(Location point, int size, DrawingCanvas canvas) {
		int cellSize = (int)(Math.log10(size*size)+1)*DIGIT_WIDTH +GAP;
		int totalSize = cellSize * size;

		double cornerX = point.getX();
		double cornerY = point.getY();

		// draw the vertical lines
		for (double x = cornerX; x <= cornerX + totalSize; x = x + cellSize) {
			new Line(x, cornerY, x, cornerY + totalSize, canvas);
		}

		// draw the horizontal lines
		for (double y = cornerY; y <= cornerY + totalSize; y = y + cellSize) {
			new Line(cornerX, y, cornerX + totalSize, y, canvas);
		}

		// fill in the grid
		for (int row = 0; row < size; row++) {
			for (int col = 0; col < size; col++) {
				new Text(magicArray[row][col], cornerX + col * cellSize
						+ OFFSET, cornerY + row * cellSize + OFFSET, canvas);
			}
		}

	}

}
