"""
AbuLang GUI Terminal - Redirect terminal commands to GUI
When GUI is active, show(), ask(), and other commands render to GUI instead of console
"""

import tkinter as tk
from tkinter import simpledialog, messagebox
from .gui_manager import GUIManager, obj, draw, rgb


class GUITerminal:
    """Terminal interface that renders to GUI"""
    
    def __init__(self, gui_manager):
        """Initialize GUI Terminal"""
        self.gui = gui_manager
        self.y_position = 20
        self.line_height = 30
        self.answers = {}
        self.current_answer = None
    
    def show(self, *args, **kwargs):
        """Display text as label on GUI"""
        text = ' '.join(str(arg) for arg in args)
        
        # Create label
        label = tk.Label(
            self.gui.root,
            text=text,
            font=("Arial", 12),
            bg="white",
            wraplength=700
        )
        label.place(x=20, y=self.y_position, width=760, height=self.line_height)
        
        self.y_position += self.line_height + 5
        self._check_scroll()
        
        return text
    
    def ask(self, prompt=""):
        """Display question with entry box"""
        frame = tk.Frame(self.gui.root, bg="white")
        frame.place(x=20, y=self.y_position, width=760, height=self.line_height + 10)
        
        # Label
        label = tk.Label(frame, text=str(prompt), font=("Arial", 11), bg="white")
        label.pack(side=tk.LEFT, padx=5)
        
        # Entry
        entry = tk.Entry(frame, font=("Arial", 11), width=40)
        entry.pack(side=tk.LEFT, padx=5)
        
        self.y_position += self.line_height + 15
        self._check_scroll()
        
        # Return entry widget for later retrieval
        return entry
    
    def multiple_choice(self, question, ans1, ans2, ans3, ans4):
        """Display multiple choice question with 4 buttons"""
        # Question label
        q_label = tk.Label(
            self.gui.root,
            text=str(question),
            font=("Arial", 12, "bold"),
            bg="white",
            wraplength=700
        )
        q_label.place(x=20, y=self.y_position, width=760, height=self.line_height)
        
        self.y_position += self.line_height + 10
        
        # Store selected answer
        selected = tk.StringVar()
        
        # Create buttons
        answers = [ans1, ans2, ans3, ans4]
        button_width = 180
        button_height = 40
        x_positions = [20, 210, 400, 590]
        
        for i, answer in enumerate(answers):
            btn = tk.Button(
                self.gui.root,
                text=str(answer),
                font=("Arial", 10),
                width=20,
                height=2,
                command=lambda ans=answer: selected.set(ans)
            )
            btn.place(x=x_positions[i], y=self.y_position, width=button_width, height=button_height)
        
        self.y_position += button_height + 15
        self._check_scroll()
        
        self.current_answer = selected
        return selected
    
    def save_ans(self, filename, data):
        """Save answer/data to file"""
        try:
            with open(filename, 'w') as f:
                f.write(str(data))
            self.show(f"Saved to {filename}")
            return True
        except Exception as e:
            self.show(f"Error saving: {e}")
            return False
    
    def _check_scroll(self):
        """Check if we need to scroll"""
        if self.y_position > self.gui.height - 100:
            # Reset position (in real app, would implement scrolling)
            self.y_position = 20
            self.gui.canvas.delete("all")
    
    def get_answer(self):
        """Get the current selected answer"""
        if self.current_answer:
            return self.current_answer.get()
        return None


def enable_gui_terminal(gui_manager):
    """Enable GUI terminal mode for a GUI manager"""
    terminal = GUITerminal(gui_manager)
    
    # Override builtins to use GUI
    import builtins
    
    original_show = builtins.show
    original_ask = builtins.ask
    
    def gui_show(*args, **kwargs):
        return terminal.show(*args, **kwargs)
    
    def gui_ask(prompt=""):
        entry = terminal.ask(prompt)
        # For now, return the entry widget
        # In real usage, would need to wait for user input
        return entry
    
    builtins.show = gui_show
    builtins.ask = gui_ask
    builtins.multiple_choice = terminal.multiple_choice
    builtins.save_ans = terminal.save_ans
    
    return terminal
