import pygame
pygame.init()

class Pattern(object):
    """
    Defines a surface with separate rows, which when drawn in sequence make a pattern
    """
    def __init__(self, width, height, bg_colour=(255,255,255), pat_colour=(0,0,0)):
        """
        Construct a Pattern with the given width and height.
        Optional background RGB colour tuple/list will be white by default.
        Optional pattern RGB colour tuple/list will be black by default.
        """
        self.__back = pygame.Surface((width, height))
        self.__back.fill(bg_colour)
        self.__screen = self.__back
        self.__current_row = 0
        self.__bg_colour = bg_colour
        self.__pat_colour = pat_colour

        #self.__screen.blit(self.__back, (0,0))
        #pygame.display.flip()
    
    def add_row(self, row):
        """
        Add the row (list of bools) to the pattern at the next row position.
        Once the last row has been added the window will wait to be closed
        before returning to calling code.
        """
        #If this is the first row, set-up the display and place the background
        if self.__current_row == 0:
            self.__screen = pygame.display.set_mode(self.__back.get_size())
            self.__screen.blit(self.__back, (0,0))
            
        if len(row) != self.__back.get_width():
            raise ValueError("Length of row argument does not match Pattern width")
        else:
            row_surf = pygame.Surface((len(row), 1)).convert()
            row_surf.fill(self.__bg_colour)
            for x in range(len(row)):
                if row[x] == True:
                    row_surf.set_at((x, 0), self.__pat_colour)
            self.__screen.blit(row_surf, (0, self.__current_row))
            pygame.display.flip()
            self.__current_row += 1

        #If we have hit the last row, display the window
        if self.__current_row == self.__back.get_height():
            pygame.display.set_caption("Nice pattern!  Close window to quit.")
            keep_going = True
            while keep_going:
                for ev in pygame.event.get():
                    if ev.type == pygame.QUIT:
                        keep_going = False
                        pygame.display.quit() #closes the display window
        

    def save(self, file_name):
        """
        Save the current pattern as an image with the given file_name.
        Supported types: .png, .bmp, .jpg
        """
        pygame.image.save(self.__screen, file_name)