"""
Export handler for PyUCC GUI.
Handles exporting results to CSV and other formats.
"""
from tkinter import filedialog, messagebox


class ExportHandler:
	"""Handles export functionality for results."""
	
	def __init__(self, gui_app):
		"""
		Args:
			gui_app: Reference to the main GUI application instance
		"""
		self.app = gui_app
	
	def export_to_csv(self):
		"""Export current results tree to CSV file."""
		from ..utils.csv_exporter import export_rows_to_csv
		
		path = filedialog.asksaveasfilename(
			defaultextension=".csv",
			filetypes=[("CSV files", "*.csv"), ("All files", "*")]
		)
		
		if not path:
			return
		
		headers = [c for c in self.app.results_tree['columns']]
		rows = (self.app.results_tree.item(child, 'values') for child in self.app.results_tree.get_children())
		
		try:
			written = export_rows_to_csv(path, headers, rows)
			messagebox.showinfo("Export", f"Exported {written} rows to {path}")
		except Exception as e:
			messagebox.showerror("Export Error", str(e))
