import tkinter as tk
from modules.module import Module
import os
import random
import functools
import pyautogui
from modules.util import HighlightButton


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

        image_collections = []
        for folder in os.listdir(os.path.join("images", "keypad")):
            image_strip = []
            for file in os.listdir(os.path.join("images", "keypad", folder)):
                image_path = os.path.join("images", "keypad", folder, file)
                image_strip.append(image_path)

            image_collections.append(image_strip)


        if self.game_manager.config:
            strip = image_collections[self.game_manager.config[self.game_manager.cur_puzzle][str(self)]["strip_num"]]
            image_indices = self.game_manager.config[self.game_manager.cur_puzzle][str(self)]["image_nums"]
            images = [strip[x] for x in image_indices]
        else:
            strip = random.choice(image_collections)
            images = random.sample(strip, 4)
            random.shuffle(images)

        correct_order = sorted(images)
        self.correct_buttons = [images.index(x) for x in correct_order]
        self.current_index = 0

        self.buttons = []
        for i in range(len(images)):
            image = tk.PhotoImage(file=images[i])
            resized = image.subsample(3)
            button = HighlightButton(self, 40 + 180 * (i // 2), 100 + 180 * (i % 2), 166,
                                     166, image=resized, command=functools.partial(self.on_image_click, None, i))
            button.image = resized
            self.buttons.append(button)

        self.max_score = 0

    def send_info_to_solver(self):
        button_names = ["press_top_left_button", "press_bottom_left_button",
                        "press_top_right_button", "press_bottom_right_button"]
        for i in range(len(self.buttons)):
            self.actions.append(
                {"type": "button", "name": f"{button_names[i]}", "x_coord": self.buttons[i].x_coord, "y_coord": self.buttons[i].y_coord})
        super().send_info_to_solver()

    def click_button(self, x, y):
        pyautogui.moveTo(x, y, duration=0.1)
        pyautogui.click()

    def execute_action(self, message):
        clicked = False

        messages = message.split("\n")

        if self.gui:
            for message in messages:
                for action in self.actions:
                    if message != '' and action["name"] in message:
                        self.click_button(
                            x=action['x_coord'], y=action['y_coord'])
                        clicked = True
        else:
            for message in messages:
                button_names = ["press_top_left_button", "press_bottom_left_button",
                                "press_top_right_button", "press_bottom_right_button"]
                for i, button in enumerate(button_names):
                    if message == button:
                        self.on_image_click(img_num=i)
                        clicked = True

        return clicked

    def on_image_click(self, event=None, img_num=0):
        if self.correct_buttons[self.current_index] == img_num:
            self.current_index += 1
            self.max_score = self.current_index
        else:
            self.current_index = 0
            self.score = 0
            self.log_mistake()

        if self.current_index == len(self.correct_buttons):
            self.finish_check()

    def check_correct(self):
        return True

    def get_score(self):
        return self.max_score / 4

    def __str__(self):
        return "KeyPadPuzzle"
