# export_popup.py
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import json
from .i18n import t

class ExportPopup(tk.Toplevel):
    def __init__(self, parent, tag_data):
        super().__init__(parent)
        self.parent = parent
        self.tag_data = tag_data

        self.title(t('export_popup.window_title'))
        self.geometry("500x300")
        self.transient(parent)
        self.grab_set()

        main_frame = ttk.Frame(self, padding="10")
        main_frame.pack(fill="both", expand=True)
        main_frame.rowconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)

        # Formata os dados no padrão JSON
        if isinstance(tag_data, list):
            # Múltiplas tags
            self.json_content = json.dumps(tag_data, indent=4, ensure_ascii=False)
        else:
            # Uma única tag (compatibilidade)
            self.json_content = json.dumps(tag_data, indent=4, ensure_ascii=False)

        self.text_area = tk.Text(main_frame, wrap="word", height=5)
        self.text_area.grid(row=0, column=0, sticky="nsew")
        self.text_area.insert("1.0", self.json_content)
        self.text_area.config(state="disabled")

        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=1, column=0, pady=(10, 0))

        ttk.Button(button_frame, text=t('export_popup.btn_copy_clipboard'), command=self._copy_to_clipboard).pack(side="left", padx=5)
        ttk.Button(button_frame, text=t('export_popup.btn_save_file'), command=self._save_to_file).pack(side="left", padx=5)
        ttk.Button(button_frame, text=t('export_popup.btn_close'), command=self.destroy).pack(side="left", padx=5)

    def _copy_to_clipboard(self):
        self.clipboard_clear()
        self.clipboard_append(self.json_content)
        messagebox.showinfo(t('export_popup.clipboard_ok_title'), t('export_popup.clipboard_ok_msg'), parent=self)

    def _save_to_file(self):
        # Define nome do arquivo baseado no número de tags
        if isinstance(self.tag_data, list):
            filename = f"tags_export_{len(self.tag_data)}.json"
        else:
            filename = f"{self.tag_data.get('epc', 'tag')}.json"
            
        filepath = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[
                (t('export_popup.filetype_json'), "*.json"),
                (t('export_popup.filetype_all'), "*.*"),
            ],
            initialfile=filename,
            parent=self
        )
        if filepath:
            try:
                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(self.json_content)
                messagebox.showinfo(t('export_popup.save_ok_title'), t('export_popup.save_ok_msg'), parent=self)
            except IOError as e:
                messagebox.showerror(
                    t('export_popup.save_error_title'),
                    t('export_popup.save_error_msg').format(error=str(e)),
                    parent=self)