import tkinter as tk
from tkinter import Button, simpledialog, messagebox

class TopmostForm:
    def __init__(self, root):
        self.root = root
        self.root.title("Quiz Form")
        self.admin_button = Button(self.root, text="Admin", state="disabled", command=self.admin_access)
        self.admin_button.pack()
        self.timer_id = self.root.after(5000, self.enable_admin_button)
        
        # Disable resizing
        self.root.resizable(False, False)
        
        # Get screen dimensions
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        
        # Set initial window size to maximum screen resolution
        self.root.geometry(f"{screen_width}x{screen_height}+0+0")
        
        self.score = 0
        self.is_timer_active = False
        self.timer_id = None
        self.timer_count = 5  # Timer count in seconds
        self.admin_password = "admin123"
        
        self.admin_panel_open = False
        self.admin_panel = None
        
        self.test_target_percentage = 60  # Set the test target percentage here
        
        self.retake_button = None
        
        # Create questions and answers
        self.questions = [
            {
                'question': "What is the capital of France?",
                'choices': ["London", "Paris", "Berlin"],
                'correct': 1
            },
            {
                'question': "Which planet is known as the Red Planet?",
                'choices': ["Mars", "Earth", "Venus"],
                'correct': 0
            }
        ]
        
        self.current_question = 0
        
        # Create a label widget for questions
        self.question_label = tk.Label(root, text="", font=("Helvetica", 16))
        self.question_label.pack(padx=20, pady=20)
        
        # Create radio buttons for answer choices
        self.choice_var = tk.IntVar()
        self.choice_buttons = []
        for i in range(3):
            button = tk.Radiobutton(root, text="", variable=self.choice_var, value=i)
            button.pack(anchor="w", padx=20)
            self.choice_buttons.append(button)
        
        # Create a Submit button
        submit_button = tk.Button(root, text="Submit", command=self.submit_answer)
        submit_button.pack(pady=20)
        
        # Create a Retake button
        self.retake_button = tk.Button(root, text="Retake", command=self.retake_test, state=tk.DISABLED)
        self.retake_button.pack(pady=10)
        
       
        
        # Create a Score label
        self.score_label = tk.Label(root, text="Score: 0")
        self.score_label.pack()
        
        # Create a Timer label
        self.timer_label = tk.Label(root, text="", font=("Helvetica", 14))
        self.timer_label.pack()
        
        # Make the form topmost
        self.root.wm_attributes("-topmost", 1)
        
        # Disable close button
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)
        
        # Bind a function to handle the form's visibility when losing focus
        self.root.bind("<FocusOut>", self.on_focus_out)
        
        self.disable_minimize_timer()
        
        # Bind a function to handle the form's movement
        self.root.bind("<Configure>", self.on_configure)
        
        self.show_question(self.current_question)
        
    def on_focus_out(self, event):
        # When the form loses focus, bring it back to the top
        self.root.focus_force()
        
    def on_close(self):
        # Prevent the form from closing
        pass
    
    def on_configure(self, event):
        # Reset the window position to its original position if moving is attempted
        if self.is_timer_active:
            self.root.geometry("1080x768+0+0")
        
    def disable_minimize_timer(self):
        if not self.is_timer_active:
            self.is_timer_active = True
            
            # Disable window decorations and prevent moving
            self.root.overrideredirect(1)
            
            # Schedule re-enabling of window decorations and moving after 30 seconds
            self.timer_id = self.root.after(5000, self.enable_minimize)
            
            # Disable the admin button when the timer is running
            self.admin_button.config(state=tk.DISABLED)
             
            
            
        else:
            # If the timer is already running, cancel it
            self.root.after_cancel(self.timer_id)
            self.enable_minimize()
            # Enable the admin button when the timer is stopped
            self.admin_button.config(state=tk.NORMAL)

                 

    def enable_minimize(self):
        # Restore window decorations and allow moving
        self.root.overrideredirect(0)
        self.is_timer_active = False
        self.timer_id = None
        self.timer_label.config(text="")  # Clear the timer label
        
    def update_timer_label(self):
        if self.timer_id is not None and self.timer_count > 0:
            self.timer_label.config(text=f"Time left: {self.timer_count} seconds")
            self.timer_count -= 1
            self.timer_id = self.root.after(1000, self.update_timer_label)
        else:
            self.timer_label.config(text="")
            self.retake_button.config(state=tk.NORMAL)
            
            self.show_result()
            self.enable_minimize()  # Stop the timer if it reaches zero
        
    def show_question(self, question_index):
        question_data = self.questions[question_index]
        question_text = question_data['question']
        self.question_label.config(text=question_text)
        
        for i in range(3):
            self.choice_buttons[i].config(text=question_data['choices'][i])
        
    def submit_answer(self):
        selected_choice = self.choice_var.get()
        correct_choice = self.questions[self.current_question]['correct']
        
        if selected_choice == correct_choice:
            self.score += 1
            messagebox.showinfo("Correct", "Your answer is correct!")
            
        else:
            messagebox.showinfo("Incorrect", "Your answer is incorrect.")
        
        self.current_question += 1
        if self.current_question < len(self.questions):
            self.show_question(self.current_question)
        else:
            self.show_result()
            
    def show_result(self):
        percentage_obtained = (self.score / len(self.questions)) * 100
        self.score_label.config(text=f"Score: {self.score} ({percentage_obtained:.2f}%)")
        if percentage_obtained >= self.test_target_percentage:
            pass_fail = "Pass"
            self.retake_button.config(state=tk.DISABLED)
            
            self.enable_minimize()  # Stop the timer if user passes
        else:
            pass_fail = "Fail"
            self.retake_button.config(state=tk.NORMAL)
            
        self.score_label.config(text=f"Score: {self.score} ({percentage_obtained:.2f}% - {pass_fail})")
    
    def admin_access(self):
        password = simpledialog.askstring("Admin Access", "Enter admin password:")
        if password == self.admin_password:
            self.admin_panel = tk.Toplevel(self.root)
            self.admin_panel.title("Admin Panel")
            self.admin_panel.geometry("300x200")
            self.admin_panel.protocol("WM_DELETE_WINDOW", self.close_admin_panel)
            
            self.admin_panel_open = True
            self.admin_panel.lift(self.root)
            
            # Make the admin panel topmost
            self.admin_panel.wm_attributes("-topmost", 1)
            
            # Disable the admin button when the admin panel is open
            self.admin_button.config(state=tk.DISABLED)
              
            # Wait until the admin panel is closed
            self.admin_panel.wait_window()

        else:
            messagebox.showinfo("Access Denied", "Incorrect admin password.")
            
    def close_admin_panel(self):
        self.admin_panel_open = False
        self.admin_panel.destroy()
        self.admin_panel = None
        
        # Enable the admin button when the admin panel is closed, unless the timer is running
        if not self.is_timer_active:
            self.admin_button.config(state=tk.NORMAL)
    
    def retake_test(self):
        self.score = 0
        self.current_question = 0
        self.retake_button.config(state=tk.DISABLED)
        
        self.show_question(self.current_question)
        self.score_label.config(text="Score: 0")
        self.timer_count = 30  # Reset timer count
    
    def enable_admin_button(self):
        # Enable the admin button
        self.admin_button.config(state="normal")

    def start(self):
        self.root.mainloop()


if __name__ == "__main__":
    root = tk.Tk()
    app = TopmostForm(root)
    root.mainloop()