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

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

        self.title("Export Tags to JSON")
        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="Copy to Clipboard", command=self._copy_to_clipboard).pack(side="left", padx=5)
        ttk.Button(button_frame, text="Save to File...", command=self._save_to_file).pack(side="left", padx=5)
        ttk.Button(button_frame, text="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("Success", "JSON data copied to clipboard.", 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=[("JSON Files", "*.json"), ("All Files", "*.*")],
            initialfile=filename,
            parent=self
        )
        if filepath:
            try:
                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(self.json_content)
                messagebox.showinfo("Success", "File saved successfully.", parent=self)
            except IOError as e:
                messagebox.showerror("Error", f"Could not save file:\n{e}", parent=self)