import pygame


class Board:
    def __init__(self, width, height, screen):
        self.width = width
        self.height = height
        self.board = [[1] * width for _ in range(height)]
        self.left = 10
        self.top = 10
        self.cell_size = 30
        self.screen = screen

    def render(self):
        for y in range(self.height):
            for x in range(self.width):
                pygame.draw.rect(self.screen, pygame.Color(255, 255, 255), (
                    x * self.cell_size + self.left, y * self.cell_size + self.top, self.cell_size, self.cell_size),
                                 self.board[y][x])

    def set_view(self, left, top, cell_size):
        self.left = left
        self.top = top
        self.cell_size = cell_size

    def on_click(self, cell_coords):
        for x in range(self.height):
            self.board[x][cell_coords[1]] = (self.board[x][cell_coords[1]] + 1) % 2
        for y in range(self.width):
            self.board[cell_coords[0]][y] = (self.board[cell_coords[0]][y] + 1) % 2
        self.board[cell_coords[0]][cell_coords[1]] = (self.board[cell_coords[0]][cell_coords[1]] + 1) % 2

    def get_cell(self, mouse_pos):
        if self.left <= mouse_pos[1] < self.left + self.height * self.cell_size and \
                self.top <= mouse_pos[0] < self.top + self.width * self.cell_size:
            return int((mouse_pos[1] - self.left) / self.cell_size), int((mouse_pos[0] - self.top) / self.cell_size)
        else:
            return None

    def get_click(self, mouse_pos):
        cell = self.get_cell(mouse_pos)
        if cell is not None:
            self.on_click(cell)
