# rename_popup.py
import tkinter as tk
from tkinter import ttk, messagebox
from .i18n import get_translator, t

class RenamePopup(tk.Toplevel):
    def __init__(self, parent, db_interface, tag_epc, current_name):
        super().__init__(parent)
        self.parent = parent
        self.db_interface = db_interface
        self.tag_epc = tag_epc

        self.translator = get_translator()
        self.title(t('rename.title'))
        self.geometry("350x150")
        self.transient(parent)
        self.grab_set()
        
        main_frame = ttk.Frame(self, padding="10")
        main_frame.pack(fill="both", expand=True)
        main_frame.columnconfigure(1, weight=1)

        # Label para o EPC (não editável)
        ttk.Label(main_frame, text=t('rename.epc')).grid(row=0, column=0, sticky="w", pady=5)
        epc_label = ttk.Label(main_frame, text=self.tag_epc, font=("Consolas", 9))
        epc_label.grid(row=0, column=1, sticky="w", pady=5)

        # Entrada para o novo nome da tag
        ttk.Label(main_frame, text=t('rename.tag_name')).grid(row=1, column=0, sticky="w", pady=5)
        self.name_var = tk.StringVar(value=current_name)
        self.name_entry = ttk.Entry(main_frame, textvariable=self.name_var, width=30)
        self.name_entry.grid(row=1, column=1, sticky="ew", pady=5)
        self.name_entry.focus_set()
        self.name_entry.select_range(0, 'end')

        # Frame para os botões
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=2, column=0, columnspan=2, pady=10)

        save_button = ttk.Button(button_frame, text=t('rename.save'), command=self.save_and_close)
        save_button.pack(side="left", padx=5)
        cancel_button = ttk.Button(button_frame, text=t('rename.cancel'), command=self.destroy)
        cancel_button.pack(side="left", padx=5)
        
        # Binds para Enter e Esc
        self.bind("<Return>", lambda event: self.save_and_close())
        self.bind("<Escape>", lambda event: self.destroy())

    def save_and_close(self):
        new_name = self.name_var.get().strip()
        if not new_name:
            messagebox.showwarning(t('rename.error_empty_title'), t('rename.error_empty_msg'), parent=self)
            return
        
        # CORREÇÃO: Validação do apelido (máximo 4 caracteres)
        if len(new_name) > 4:
            messagebox.showerror(t('rename.error_max_length_title'), t('rename.error_max_length_msg'), parent=self)
            return

        # Chama a função de atualização do banco de dados
        success = self.db_interface.update_tag_name(self.tag_epc, new_name)
        
        if success:
            self.destroy() # Fecha o popup
        else:
            messagebox.showerror(t('rename.error_database_title'), t('rename.error_database_msg'), parent=self)