# Tic Tac Toe board class
"""Extends the Board class with specific features
required for Tic Tac Toe"""

# import modules and classes
from graphics import *
from tttletter import TTTLetter
from board import Board

class TTTBoard(Board):
    """TTT Board class implements the functionality of a
    Tic Tac Toe board. It inherits from the Board class and
    extends it by creating a grid of TTTLetters."""

    __slots__ = ['_grid']

    def __init__(self, win):
        super().__init__(win)

        # initialize a grid of TTTLetters (list of lists)
        self._grid = []
        for col in range(self._cols):
            grid_col = []
            # next part could be a list comprehension!
            for row in range(self._rows):
                # create new TTTLetter, specifying grid coord
                letter = TTTLetter(win, col, row)

                # add TTTLetter to column
                grid_col.append(letter)

            # add column to grid
            self._grid.append(grid_col)

    def getTTTLetterAtPosition(self, position):
        """Returns the TTTLetter at grid position (a tuple)"""
        (col, row) = position
        return self._grid[col][row]

    def getTTTLetterAtPoint(self, point):
        """Returns the TTTLetter at point (a screen coord tuple)"""
        (col, row) = self.getPosition( (point.getX(), point.getY()) )
        return self._grid[col][row]

    # reset all letter objects in grid
    def reset(self):
        """Clears the TTT board by clearing letters."""
        for x in range(self._cols):
            for y in range(self._rows):
                # get letter out of grid and reset it
                let = self._grid[x][y]
                let.setLetter("")


    # checking for win methods:
    def _checkRows(self, letter):
        """Check rows for a win (3 in a row)."""
        for row in range(self._rows):
            count = 0
            for col in range(self._cols):
                tttLet = self._grid[col][row]

                # check how many times letter appears
                if tttLet.getLetter() == letter:
                    count +=1

            # if this is a winning row
            if count == self._rows:
                return True

        # no winning row found
        return False

    def _checkCols(self, letter):
        """Check columns for a win (3 in a row)."""
        for col in range(self._cols):
            count = 0
            for row in range(self._rows):
                tttLet = self._grid[col][row]

                # check how many times letter appears
                if tttLet.getLetter() == letter:
                    count +=1

            # if this is a winning row
            if count == self._cols:
                return True

        # if no winning rows
        return False

    def _checkDiagonals(self, letter):
        """Check diagonals for a win (3 in a row)."""
        # counts for primary and secondary diagonal
        countPrimary, countSecond = 0, 0

        for col in range(self._cols):
            for row in range(self._rows):
                tttLet = self._grid[col][row]

                # update count for primary diagonal
                if (row == col and tttLet.getLetter() == letter):
                    countPrimary += 1

                # update count for secondary diagonal
                if (row + col == self._rows - 1 and tttLet.getLetter() == letter):
                    countSecond += 1

        # return true if either return in win
        return countPrimary == self.getRows() or countSecond == self.getRows()


    def checkForWin(self, letter):
        """Check board for a win."""
        rowWin = self._checkRows(letter)
        colWin = self._checkCols(letter)
        diagWin = self._checkDiagonals(letter)

        return rowWin or colWin or diagWin

if __name__ == "__main__":
    win = GraphWin("Tic Tac Toe", 400, 400)
    board = TTTBoard(win)

    keepGoing = True
    while keepGoing:
        point = win.getMouse()
        if board.inGrid(point):
            position = board.getPosition((point.getX(), point.getY()))
            print("{}".format(position))
        elif board.inExit(point):
            keepGoing = False
