import glob
from PIL import Image
from random import randrange
from uuid import uuid4

class Bingo:
    """Class which allows creation and cleanup of F1 bingo card images."""
    def __init__(self):
        self.LAYOUT_WIDTH = 88
        self.X_OFFSET  = 10
        self.Y_OFFSET = 110
        self.SQUARES_PATH = "bingo_images/squares/*.png"
        self.FREE_SQUARES_PATH = "bingo_images/free_squares/*.png"
        self.BLANK_CARD_PATH = "bingo_images/card_blank.png"
        self.TEMP_FOLDER = "bingo_images/temp/"

    def get_card(self):
        square_files = glob.glob(self.SQUARES_PATH)
        free_square_files = glob.glob(self.FREE_SQUARES_PATH)
        used_files = set()

        with Image.open(self.BLANK_CARD_PATH) as card_img:
            card_img.load()
            card_img = card_img.convert('RGBA')

        # Fill the grid
        for y in range(5):
            for x in range(5):
                square_file = ""
                # If this is the center square, pick a random free square
                if x == 2 and y == 2:
                    square_file = \
                        free_square_files[randrange(len(free_square_files))]

                # otherwise, find a random file that hasn't been used yet
                else:
                    rand_file_idx = randrange(len(square_files))
                    while rand_file_idx in used_files:
                        rand_file_idx = randrange(len(square_files))

                    square_file = square_files[rand_file_idx]
                    used_files.add(rand_file_idx)
                
                with Image.open(square_file) as square:
            
                    position = (self.X_OFFSET + (x * self.LAYOUT_WIDTH),
                                self.Y_OFFSET + (y * self.LAYOUT_WIDTH))

                    card_img.paste(square, position, square)

        # Write image to temp file
        outfile = "".join((self.TEMP_FOLDER, str(uuid4()), ".png"))
        print(f"{outfile=}")
        card_img.save(outfile)
        return outfile

