# -*- coding: utf-8 -*-
"""
Created on Wed May 22 11:27:06 2024

@author: Stéphane Pasquet
@url : https://www.mathweb.fr/euclide/un-jeu-de-memoire/
"""

import pygame
import random
import os
import glob
import time

class MemoryGame:
    def __init__(self, level):
        # Initialisation de Pygame
        pygame.init()
        # Couleurs
        self.white = (230, 230, 230)
        self.black = (0, 0, 0)
        self.gray = (200, 200, 200)
        self.level = level
        self.grid_size, self.pairs = self.get_grid_params()
        self.icon_size = 48
        self.margin = 5
        self.window_width = self.grid_size * (self.icon_size + self.margin) + self.margin
        self.window_height = self.grid_size * (self.icon_size + self.margin) + self.margin

        # Réinitialisation de la fenêtre avec les nouvelles dimensions
        self.window = pygame.display.set_mode((self.window_width, self.window_height))
        self.iconwindow = pygame.image.load("memorypix.ico")
        pygame.display.set_icon(self.iconwindow)
        pygame.display.set_caption("Memory'Pix")

        # Police pour le texte
        self.font = pygame.font.Font(None, 24)

        # icones disponibles
        self.icones_dispo = self.disponible_icons()
        
        # Construction de la grille
        self.grid = [[None for _ in range(self.grid_size)] for _ in range(self.grid_size)]
        self.construct_grid()
        
        # Gestion de l'état du jeu
        self.revealed = [[False for _ in range(self.grid_size)] for _ in range(self.grid_size)]
        self.first_click = None
        self.second_click = None
        self.score = 0
        
    def disponible_icons(self):
        # liste de tous les icones disponibles dans le dossier "icones/"
        icons_dispo = []
        search_pattern = os.path.join('icons', '*.png')
        png_files = glob.glob(search_pattern)
        for png_file in png_files:
            icons_dispo.append(png_file)
        return icons_dispo

    def construct_grid(self):
        list_tmp = self.icones_dispo.copy()
        list_icons = []
        
        for _ in range(self.pairs):
            i = random.randint(0, len(list_tmp)-1)
            list_icons.extend([list_tmp[i], list_tmp[i]])
            list_tmp.pop(i)
            
        #ajout = [None] * ((self.grid_size)**2 - len(list_icons))
        #list_icons.extend(ajout)
        random.shuffle(list_icons)
        
        i = 0
        
        for line in range(self.grid_size):
            for column in range(self.grid_size):
                self.grid[line][column] = list_icons[i]
                i += 1
        
    def get_grid_params(self):
        if self.level == "Facile":
            return 4, 8  # 4x4 grille, 8 paires d'icônes
        elif self.level == "Moyen":
            return 6, 18  # 6x6 grille, 18 paires d'icônes
        elif self.level == "Difficile":
            return 8, 32  # 8x8 grille, 32 paires d'icônes

    def draw_grid(self):
        self.window.fill(self.white)
        
        for row in range(self.grid_size):
            for col in range(self.grid_size):
                x = col * (self.icon_size + self.margin) + self.margin
                y = row * (self.icon_size + self.margin) + self.margin
                icon_path = self.grid[row][col]
                if self.revealed[row][col] and icon_path:
                    icon_image = pygame.image.load(icon_path)
                    icon_image = pygame.transform.scale(icon_image, (self.icon_size, self.icon_size))
                    self.window.blit(icon_image, (x, y))
                else:
                    pygame.draw.rect(self.window, self.gray, (x, y, self.icon_size, self.icon_size))

        pygame.display.update()

    def run(self):       
        # Afficher la grille pendant 10 secondes
        self.revealed = [[True for _ in range(self.grid_size)] for _ in range(self.grid_size)]
        self.draw_grid()
        match self.level:
            case 'Facile': pygame.time.wait(10000)  # Affiche la grille pendant 10 secondes
            case 'Moyen': pygame.time.wait(15000)  # Affiche la grille pendant 15 secondes
            case 'Difficile': pygame.time.wait(20000)  # Affiche la grille pendant 15 secondes
        
        # Cacher toutes les icônes
        self.revealed = [[False for _ in range(self.grid_size)] for _ in range(self.grid_size)]
        self.draw_grid()  # Cache la grille après 10 secondes
        self.time_start = time.time()

        running = True
        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos
                    col = x // (self.icon_size + self.margin)
                    row = y // (self.icon_size + self.margin)
                    if not self.revealed[row][col]:
                        self.revealed[row][col] = True
                        self.draw_grid()
                        if self.first_click is None:
                            self.first_click = (row, col)
                        elif self.second_click is None:
                            self.second_click = (row, col)
                            self.check_match()
                            if self.score == self.pairs:
                                running = False  # Toutes les paires ont été trouvées
            self.draw_grid()
        
        self.time_end = time.time()
        pygame.quit()
        return int(self.time_end - self.time_start) , self.score, self.pairs

    def check_match(self):
        first_row, first_col = self.first_click
        second_row, second_col = self.second_click
        if self.grid[first_row][first_col] == self.grid[second_row][second_col]:
            self.score += 1
        else:
            pygame.time.wait(1000)  # Attendre 1 seconde pour montrer les icônes non correspondantes
            self.revealed[first_row][first_col] = False
            self.revealed[second_row][second_col] = False
        self.first_click = None
        self.second_click = None