import tkinter as tk
from terminal_commands import handle_command as handle_command_module

# === Состояние подключения ===
connected_server = {}

# Функция вставки текста в защищённый Text
def safe_insert(text_widget, text, tag=None):
    text_widget.config(state="normal")
    if tag:
        text_widget.insert(tk.END, text, tag)
    else:
        text_widget.insert(tk.END, text)
    text_widget.see(tk.END)
    text_widget.config(state="disabled")

# Обработчик команд
def handle_command(cmd):
    handle_command_module(
        cmd,
        connected_server,
        lambda text, tag="system": safe_insert(output, text, tag),
        clear_screen_callback=lambda: clear_output(),
        exit_callback=lambda: root.quit()
    )

def clear_output():
    output.config(state="normal")
    output.delete("1.0", tk.END)
    output.config(state="disabled")

def run_command(event=None):
    command = entry.get().strip()
    if command:
        safe_insert(output, f"\n$ {command}\n", "user")
        handle_command(command)
    entry.delete(0, tk.END)

def on_ctrl_d(event):
    handle_command("back")
    return "break"

root = tk.Tk()
root.title("0x0F - Linux Terminal")
root.configure(bg='black')
root.attributes('-fullscreen', True)
root.bind("<Control-d>", on_ctrl_d)

icon = tk.PhotoImage(file='termnal_icon.png')
root.iconphoto(True, icon)

output = tk.Text(root,
                 bg="black",
                 fg="#00FF00",
                 insertbackground="#00FF00",
                 font=("DejaVu Sans Mono", 14),
                 undo=True,
                 wrap='word',
                 borderwidth=0,
                 highlightthickness=0)
output.pack(fill=tk.BOTH, expand=True)
output.config(state="disabled")

output.tag_config("user", foreground="#55FF55")
output.tag_config("system", foreground="#00FF00")
output.tag_config("error", foreground="#FF5555")

output.config(state="normal")
output.insert(tk.END, "Добро пожаловать в терминал 0x0F. Введите команду (help для справки)\n", "system")
output.config(state="disabled")

entry = tk.Entry(root,
                 bg="black",
                 fg="#00FF00",
                 insertbackground="#00FF00",
                 font=("DejaVu Sans Mono", 14),
                 relief=tk.FLAT,
                 borderwidth=0)
entry.pack(fill=tk.X, side=tk.BOTTOM)
entry.bind("<Return>", run_command)
entry.focus()

root.mainloop()
