import tkinter as tk
from modules.module import Module
import os
import random
import functools
import pyautogui
import time
from modules.util import HighlightButton
from PIL import Image, ImageTk

class DogPuzzle(Module):
    def __init__(self, game_manager):
        super(DogPuzzle, self).__init__(game_manager)

        dog_images = os.listdir(os.path.join("images", "dogs"))
        if self.game_manager.config:
            sampled_image = dog_images[self.game_manager.config[self.game_manager.cur_puzzle][str(self)]["dog_image_num"]]
        else:
            sampled_image = random.choice(dog_images)

        pil_image = Image.open(os.path.join("images", "dogs", sampled_image))
        pil_image = pil_image.resize((450,300))
        tk_image = ImageTk.PhotoImage(pil_image)
        
        self.image_id = self.canvas.create_image(250, 260, image = tk_image, anchor='center')
        self.canvas.image = tk_image
        self.n_dogs = int(sampled_image.split("_")[0])

        send_button = HighlightButton(
            self, self.width / 2 - 80, 425, 160, 40, text="SUBMIT", command=self.on_submit)
        self.buttons.append(send_button)

    def send_info_to_solver(self):
        for i in range(10):
            self.actions.append({"type": "press_and_hold", "name": f"press_and_hold_button_{i}_seconds", "x_coord": (
                55 + 320) / 2, "y_coord": (155 + 420) / 2})
        super().send_info_to_solver()

    def on_submit(self, event=None):
        if self.finish_check().startswith("The puzzle is solved!"):
            self.canvas.delete(self.image_id)

    def click_button(self, x, y, s):
        pyautogui.moveTo(x, y, duration=0.1)
        pyautogui.mouseDown(button='left')
        time.sleep(s)
        pyautogui.mouseUp(button='left')

    def execute_action(self, message):
        for i in range(10):
            if f"press_and_hold_button_{i}_seconds" in message:
                time.sleep(i)
                self.on_submit()
                return True

        return False

    def check_correct(self):
        timer_text = self.timer_label.cget("text")
        correct = False
        if self.n_dogs == 4 and "4" in timer_text:
            correct = True
        if self.n_dogs == 3 and "3" in timer_text:
            correct = True
        if self.n_dogs == 2 and "2" in timer_text:
            correct = True
        if self.n_dogs == 1 and "1" in timer_text:
            correct = True
        if self.n_dogs == 0 and "0" in timer_text:
            correct = True
        return correct


    def __str__(self):
        return "DogPuzzle"
