import pygame
import time


class Module:
    def __init__(self, game_manager, gui=False):
        self.game_manager = game_manager
        width = 500
        height = 500
        self.width = width
        self.height = height
        self.buttons = []

        self.mistakes = 0
        self.state = {}
        self.actions = []

        self.start_seconds = self.game_manager.total_seconds
        self.serial_number = game_manager.serial_number
        self.timer_label = game_manager.timer_label
        self.canvas = game_manager.canvas
        self.feedback = ""
        self.canvas.pack()

        if self.game_manager.use_sound:
            pygame.mixer.init()

        self.gui = False
        if self.game_manager.gui:
            self.gui = True

    # In the future, if we have a remote AI controller, may use this
    def send_info_to_solver(self):
       pass
    
    # Returns a bool indicating whether the puzzle is finished
    def check_correct(self):
        return False

    def update_feedback(self):
        self.feedback = self.finish_check()

    # Draws a red circle on the module and plays a sound to indicate a mistake was made
    # Also increments the total mistakes on the module by 1
    def log_mistake(self):
        if self.game_manager.use_sound:
            sound = pygame.mixer.Sound("sounds/wrong.mp3")
            sound.set_volume(0.1)

            # Play the sound
            sound.play()

        self.mistakes += 1
        self.canvas.create_oval(
            self.width - 100, 100, self.width - 50, 50, outline="black", width=2, fill="red")

        if self.game_manager.socket != None:
            time.sleep(1)
            self.send_info_to_solver()

        self.canvas.after(1000, lambda: self.canvas.create_oval(
            self.width - 100, 100, self.width - 50, 50, outline="black", width=2, fill="gray"))

    def finish_check(self):
        correct = self.check_correct()
        if correct:
            self.canvas.create_oval(
                self.width - 100, 100, self.width - 50, 50, outline="black", width=2, fill="green")
            print(f"Made {self.mistakes} mistakes solving this puzzle")
            print(
                f"Took {self.start_seconds - self.game_manager.total_seconds} seconds to solve this puzzle")

            if self.game_manager.use_sound:
                sound = pygame.mixer.Sound("sounds/correct.mp3")
                sound.play()

            for button in self.buttons:
                button.destroy()

            if hasattr(self, 'stage_labels'):
                print(self.stage_labels)
                for label in self.stage_labels:
                    label.destroy()

            self.game_manager.advance_puzzle()
            return "The puzzle is solved! Here comes a new puzzle. Let's start working on it."
        else:
            self.log_mistake()

            return "Wrong action! Please try again."

    def get_score(self):
        return None
