import random
import string
import threading
import os
import tkinter as tk
from tkinter import ttk

class WaveExecutorKeyGenerator:
    """
    Class to generate wave executor keys for Roblox.

    Attributes:
    - key_length: int
        The total length of the key to be generated.
    - segment_length: int
        The length of each segment in the key.
    - segments: int
        The number of segments in the key.
    - correct_key: str
        The correct key that will be checked against generated keys.
    - stop_event: threading.Event
        An event to signal the thread to stop.
    - automatic_clear_event: threading.Event
        An event to signal automatic clearing of wrong_keys.txt.
    """

    def __init__(self, correct_key: str):
        """
        Initializes the key generator with the correct key.

        Parameters:
        - correct_key: str
            The correct key that will be used for validation.
        """

        self.key_length = 25
        self.segment_length = 5
        self.segments = self.key_length // self.segment_length
        self.correct_key = correct_key
        self.stop_event = threading.Event()
        self.automatic_clear_event = threading.Event()

    def generate_key(self):
        """
        Generates a random key in the format XXXX-XXXX-XXXX-XXXX.

        Returns:
        - str:
            A randomly generated key.
        """

        key_segments = []
        for _ in range(self.segments):
            segment = ''.join(random.choices(string.ascii_letters + string.digits, k=self.segment_length))
            key_segments.append(segment)
        return '-'.join(key_segments)

    def start_generating(self, start_button, stop_button):
        """
        Starts the key generation process and checks for the correct key.

        Parameters:
        - start_button: ttk.Button
            The button to start the key generation.
        - stop_button: ttk.Button
            The button to stop the key generation.
        """

        self.stop_event.clear()
        self.automatic_clear_event.clear()
        start_button.configure(state='disabled', text="Generating...")
        stop_button.configure(state='normal', text="Stop")
        threading.Thread(target=self._generate_and_check_keys, args=(start_button, stop_button,)).start()
        self.schedule_automatic_clear()

    def _generate_and_check_keys(self, start_button, stop_button):
        """
        Generates keys and checks them against the correct key until stopped,
        printing messages to the console.
        """

        script_dir = os.path.dirname(os.path.abspath(__file__))
        correct_keys_file_path = os.path.join(script_dir, "correct_keys.txt")
        wrong_keys_file_path = os.path.join(script_dir, "wrong_keys.txt")

        try:
            while not self.stop_event.is_set():
                generated_key = self.generate_key()
                print(f"Generated Key: {generated_key}")

                if generated_key == self.correct_key:
                    print("Correct key found! Stopping generation.")
                    with open(correct_keys_file_path, 'a') as f:
                        f.write(generated_key + '\n')
                    self.stop_event.set()
                else:
                    with open(wrong_keys_file_path, 'a') as f:
                        f.write(generated_key + '\n')
        except Exception as e:
            print(f"An error occurred during key generation: {e}")
        finally:
            start_button.configure(state='normal', text="Start")
            stop_button.configure(state='disabled', text="Stopped")

    def stop_generating(self):
        """
        Stops the key generation process.
        """
        self.stop_event.set()

    def schedule_automatic_clear(self):
        """
        Schedules the automatic clearing of wrong_keys.txt every 3 seconds if
        automatic_clear_event is set.
        """

        if self.automatic_clear_event.is_set():
            self.clear_wrong_keys()
        if not self.stop_event.is_set():
            root.after(3000, self.schedule_automatic_clear)

    def toggle_automatic_clear(self, toggle_button):
        """
        Toggles automatic clearing of wrong_keys.txt.
        """

        if toggle_button.cget('text') == "Turn On Automatic Clear":
            toggle_button.configure(text="Turn Off Automatic Clear")
            self.automatic_clear_event.set()
            self.schedule_automatic_clear()
        else:
            toggle_button.configure(text="Turn On Automatic Clear")
            self.automatic_clear_event.clear()

    def clear_wrong_keys(self):
        """
        Clears the content of wrong_keys.txt file, leaving only one character.
        """

        script_dir = os.path.dirname(os.path.abspath(__file__))
        wrong_keys_file_path = os.path.join(script_dir, "wrong_keys.txt")

        try:
            with open(wrong_keys_file_path, 'w') as f:
                f.write("X")
            print("Successfully cleared wrong_keys.txt, leaving only one character.")
        except OSError as e:
            print(f"Error clearing wrong_keys.txt: {e}")

# Function to create a styled button with black outline
def create_styled_button(parent, text, command, state='normal'):
    style = ttk.Style()
    style.configure('Custom.TButton', font=('Arial', 12, 'bold'), foreground='black', background='#ffffff', borderwidth=2, relief='raised')
    style.map('Custom.TButton',
              foreground=[('pressed', 'black'), ('active', 'black')],
              background=[('pressed', '!disabled', '#e0e0e0'), ('active', '#ffffff')])

    button = ttk.Button(parent, text=text, style='Custom.TButton', command=command, state=state)
    return button

# Example usage
if __name__ == "__main__":
    root = tk.Tk()
    root.title("WaveKeyGen")  # Setting the window title here
    root.geometry('400x300')  # Set initial window size

    correct_key = "ABCDE-12345-FGHIJ-67890"  # Example correct key
    key_generator = WaveExecutorKeyGenerator(correct_key)

    # Generator Section
    generator_frame = ttk.LabelFrame(root, text="Generator")
    generator_frame.pack(padx=10, pady=10, fill='both', expand=True)

    def start_generation():
        key_generator.start_generating(start_button, stop_button)

    def clear_wrong_keys():
        clear_button.configure(state='disabled')  # Disable the button during cooldown

        # Countdown label for 3 seconds
        countdown_label = tk.Label(root, font=('Arial', 12), fg='red')
        countdown_label.pack(pady=10)

        def update_countdown(count):
            countdown_label.config(text=f"Cooldown: {count} seconds")
            if count > 0:
                root.after(1000, update_countdown, count - 1)
            else:
                countdown_label.pack_forget()  # Remove the countdown label
                key_generator.clear_wrong_keys()
                clear_button.configure(state='normal')  # Re-enable the button

        update_countdown(3)  # Start the countdown

    start_button = create_styled_button(generator_frame, "Start Generating", start_generation)
    start_button.pack(pady=10)

    stop_button = create_styled_button(generator_frame, "Stop", key_generator.stop_generating, state='disabled')
    stop_button.pack(pady=10)

    # Clearer Section
    clearer_frame = ttk.LabelFrame(root, text="Clearer")
    clearer_frame.pack(padx=10, pady=10, fill='both', expand=True)

    clear_button = create_styled_button(clearer_frame, "Clear Wrong Keys", clear_wrong_keys)
    clear_button.pack(pady=10)

    def toggle_automatic_clear():
        key_generator.toggle_automatic_clear(toggle_button)

    toggle_button = create_styled_button(clearer_frame, "Turn On Automatic Clear", toggle_automatic_clear)
    toggle_button.pack(pady=10)

    # Credits label positioned at the bottom-right corner
    credits_label = tk.Label(root, text="Made By jay10282", font=('Arial', 10), fg='gray')
    credits_label.place(relx=1.0, rely=1.0, anchor='se', x=-10, y=-10)

    root.mainloop()

in the button "turn on automatic clear", instead of it being a button, make it a toggle, from this guide https://www.tutorialspoint.com/how-to-create-a-tkinter-toggle-button