"""
Execution tab component for the Excel Filter GUI
"""

import tkinter as tk
from tkinter import ttk
import tkinter.font as tkfont


class ExecutionTab:
    """
    Execution tab component that shows the command and logs
    """

    def __init__(self, parent_frame, win11_colors, scale_factor=1.0, translations=None):
        """
        Initialize the execution tab

        Args:
            parent_frame: Parent frame to attach to
            win11_colors: Windows 11 color palette dictionary
            scale_factor: DPI scaling factor for high-resolution displays
            translations: Translations object for internationalization
        """
        self.frame = ttk.Frame(parent_frame)
        self.win11_colors = win11_colors
        self.scale_factor = scale_factor
        self.translations = translations

        # Variables
        self.command_var = tk.StringVar(value=self.translations.get("ready_to_execute", "Bereit zur Ausführung..."))
        self.status_var = tk.StringVar(value="🔄 " + (self.translations.get("status_ready", "Bereit")))
        self.progress_var = tk.DoubleVar(value=0.0)

        # Execution state
        self.is_executing = False

        # References to other components (will be set later)
        self.config_tab = None
        self.main_gui = None

        self.create_widgets()
    
    def create_widgets(self):
        """
        Create all widgets for the execution tab with modern design
        """
        # Scale factors for DPI-aware sizing - ensure minimum text size of 12
        scaled_padding = int(8 * self.scale_factor)
        scaled_small_padding = int(5 * self.scale_factor)
        scaled_large_padding = int(15 * self.scale_factor)
        scaled_font_size = max(int(10 * self.scale_factor), 12)
        scaled_bold_font_size = max(int(12 * self.scale_factor), 12)
        scaled_title_font_size = max(int(14 * self.scale_factor), 12)

        # Main container with minimal padding
        main_frame = ttk.Frame(self.frame)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=scaled_small_padding, pady=scaled_small_padding)

        # Status indicator at the top
        status_frame = ttk.Frame(main_frame)
        status_frame.pack(fill=tk.X, pady=(0, scaled_padding))

        status_icon = ttk.Label(status_frame, textvariable=self.status_var,
                               font=('Segoe UI', scaled_bold_font_size, 'bold') if 'Segoe UI' in tkfont.families() else ('Helvetica', scaled_bold_font_size, 'bold'))
        status_icon.pack(side=tk.LEFT)

        # Progress bar (initially hidden)
        self.progress_bar = ttk.Progressbar(status_frame, variable=self.progress_var, maximum=100,
                                          mode='determinate', length=int(300 * self.scale_factor))
        self.progress_bar.pack(side=tk.RIGHT, padx=(scaled_padding, 0))
        self.progress_bar.pack_forget()  # Hide initially

        # Command display with smart line breaking
        command_frame = ttk.LabelFrame(main_frame, text="🎯 " + (self.translations["command_to_execute"] if self.translations else "Auszuführender Befehl"),
                                     padding=str(scaled_padding))
        command_frame.pack(fill=tk.X, pady=(0, scaled_padding))

        # Create a text widget for better command display with line breaks
        command_text_frame = ttk.Frame(command_frame)
        command_text_frame.pack(fill=tk.X)

        self.command_text = tk.Text(command_text_frame, height=6, state=tk.DISABLED, wrap=tk.WORD,
                                  bg=self.win11_colors.get('surface', '#ffffff'),
                                  font=('Courier', scaled_font_size),
                                  borderwidth=1, relief="solid",
                                  padx=scaled_padding, pady=scaled_padding,
                                  selectbackground=self.win11_colors.get('primary', '#0078d4'))
        self.command_text.pack(fill=tk.X)

        # Execution controls frame
        controls_frame = ttk.Frame(main_frame)
        controls_frame.pack(fill=tk.X, pady=(0, scaled_large_padding))

        # Execute button with modern styling
        self.execute_button = ttk.Button(
            controls_frame,
            text="🚀 " + (self.translations["execute_button"] if self.translations else "AUSFÜHREN"),
            command=self.execute_command,
            state=tk.NORMAL
        )
        self.execute_button.pack(side=tk.TOP, pady=scaled_padding, ipadx=int(40 * self.scale_factor), ipady=int(10 * self.scale_factor))

        # Style the execute button
        style = ttk.Style()
        style.configure('Execute.TButton',
                       font=('Segoe UI', scaled_bold_font_size, 'bold') if 'Segoe UI' in tkfont.families() else ('Helvetica', scaled_bold_font_size, 'bold'),
                       padding=int(20 * self.scale_factor), borderwidth=0,
                       background=self.win11_colors['primary'],
                       foreground='white')
        style.map('Execute.TButton',
                 foreground=[('active', 'white'), ('pressed', 'white'), ('disabled', '#cccccc')],
                 background=[('active', self.win11_colors.get('primary_dark', '#005a9e')),
                            ('pressed', self.win11_colors.get('primary_dark', '#005a9e')),
                            ('disabled', '#f0f0f0')])

        self.execute_button.configure(style='Execute.TButton')

        # Log display with modern design
        log_frame = ttk.LabelFrame(main_frame, text="📋 " + (self.translations["activity_log"] if self.translations else "Aktivitätsprotokoll"),
                                 padding=str(scaled_padding))
        log_frame.pack(fill=tk.BOTH, expand=True)

        # Control buttons for log
        log_controls = ttk.Frame(log_frame)
        log_controls.pack(fill=tk.X, pady=(0, scaled_padding))

        ttk.Button(log_controls, text="🧹 " + (self.translations["clear_log"] if self.translations else "Löschen"), command=self.clear_log).pack(side=tk.LEFT, padx=(0, scaled_small_padding))
        ttk.Button(log_controls, text="💾 " + (self.translations["save_log"] if self.translations else "Speichern"), command=self.save_log).pack(side=tk.LEFT)

        # Log text with enhanced styling
        log_container = ttk.Frame(log_frame)
        log_container.pack(fill=tk.BOTH, expand=True)

        # Scrollbar
        log_scrollbar = ttk.Scrollbar(log_container)
        log_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        # Log text widget
        self.log_text = tk.Text(log_container, height=int(12 * self.scale_factor), state=tk.DISABLED,
                              wrap=tk.WORD, bg=self.win11_colors.get('surface', '#ffffff'),
                              font=('Segoe UI', scaled_font_size) if 'Segoe UI' in tkfont.families() else ('Helvetica', scaled_font_size),
                              borderwidth=1, relief="solid",
                              padx=scaled_padding, pady=scaled_padding,
                              selectbackground=self.win11_colors.get('primary', '#0078d4'),
                              selectforeground='white',
                              yscrollcommand=log_scrollbar.set)

        self.log_text.pack(fill=tk.BOTH, expand=True)
        log_scrollbar.config(command=self.log_text.yview)

        # Initial log message
        self.log_message(self.translations["ready_for_execution"] if self.translations else "Excel Filter bereit zur Ausführung")
        self.log_message(""+(self.translations["configure_and_execute"] if self.translations else "Konfigurieren Sie die Einstellungen und klicken Sie auf 'AUSFÜHREN'"))
    
    def execute_command(self):
        """Execute the command"""
        # This will be connected to the main GUI's process_file method
        if hasattr(self, 'main_gui') and self.main_gui:
            self.main_gui.process_file()
        else:
            self.log_message(self.translations["error_main_gui_not_connected"] if self.translations else "Fehler: Haupt-GUI nicht verbunden")
    
    def update_command_display(self):
        """
        Update the command display based on current configuration with smart line breaking
        """
        if not self.config_tab:
            self._set_command_text(self.translations["ready_to_execute"] if self.translations else "Bereit zur Ausführung...")
            return

        try:
            input_file = self.config_tab.input_file_var.get()
            output_file = self.config_tab.output_file_var.get()
            pattern = self.config_tab.pattern_var.get()
            sheet_name = self.config_tab.sheet_var.get()

            # Build formatted command display
            lines = []

            # Input file
            if input_file:
                lines.append(f"{self.translations['input_file_label'] if self.translations else 'Eingabedatei:'} {input_file}")
            else:
                lines.append(f"{self.translations['input_file_label'] if self.translations else 'Eingabedatei:'} {self.translations['not_selected'] if self.translations else '(nicht ausgewählt)'}")

            # Output file
            if output_file:
                lines.append(f"{self.translations['output_file_label'] if self.translations else 'Ausgabedatei:'} {output_file}")
            else:
                lines.append(f"{self.translations['output_file_label'] if self.translations else 'Ausgabedatei:'} {self.translations['not_selected'] if self.translations else '(nicht ausgewählt)'}")

            # Pattern
            if pattern:
                # Break long patterns into multiple lines if needed
                if len(pattern) > 50:
                    lines.append(f"{self.translations['search_pattern_label'] if self.translations else 'Suchmuster:'} {pattern[:47]}...")
                else:
                    lines.append(f"{self.translations['search_pattern_label'] if self.translations else 'Suchmuster:'} {pattern}")
            else:
                lines.append(f"{self.translations['search_pattern_label'] if self.translations else 'Suchmuster:'} {self.translations['not_specified'] if self.translations else '(nicht angegeben)'}")

            # Sheet name
            if sheet_name:
                lines.append(f"{self.translations['worksheet_label'] if self.translations else 'Arbeitsblatt:'} {sheet_name}")

            # Selected columns
            if hasattr(self.config_tab, 'get_selected_columns'):
                selected_columns = self.config_tab.get_selected_columns()
                if selected_columns:
                    # Format columns nicely
                    if len(selected_columns) <= 3:
                        columns_text = ", ".join(selected_columns)
                    else:
                        columns_text = f"{', '.join(selected_columns[:3])} {self.translations['more_columns'].format(count=len(selected_columns) - 3) if self.translations else f'(+{len(selected_columns) - 3} weitere)'}"
                    lines.append(f"{self.translations['columns_label'] if self.translations else 'Spalten:'} {columns_text}")

            # Numeric filter settings
            if hasattr(self.config_tab, 'get_numeric_filter_settings'):
                numeric_settings = self.config_tab.get_numeric_filter_settings()
                if numeric_settings:
                    if self.translations:
                        lines.append(f"🔢 {self.translations['numeric_filter_label'].format(column=numeric_settings['column'], operator=numeric_settings['operator'], value=numeric_settings['value'])}")
                    else:
                        lines.append(f"🔢 Numerischer Filter: {numeric_settings['column']} {numeric_settings['operator']} {numeric_settings['value']}")

            # Set the formatted command text
            self._set_command_text("\n".join(lines))

        except Exception as e:
            error_text = self.translations["error_updating_command_display"].format(error=str(e)) if self.translations else f"Fehler beim Aktualisieren der Befehlsanzeige: {e}"
            self._set_command_text(error_text)
            self.log_message(error_text)

    def _set_command_text(self, text):
        """
        Set the command text in the text widget

        Args:
            text: Text to display
        """
        self.command_text.config(state=tk.NORMAL)
        self.command_text.delete(1.0, tk.END)
        self.command_text.insert(1.0, text)
        self.command_text.config(state=tk.DISABLED)
    
    def log_message(self, message):
        """
        Log a message to the log text widget
        
        Args:
            message: Message to log
        """
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)
    
    def set_config_tab(self, config_tab):
        """
        Set the reference to the config tab

        Args:
            config_tab: Reference to the config tab component
        """
        self.config_tab = config_tab

        # Set up variable tracing to update command display when config changes
        if hasattr(config_tab, 'input_file_var'):
            config_tab.input_file_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'output_file_var'):
            config_tab.output_file_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'pattern_var'):
            config_tab.pattern_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'sheet_var'):
            config_tab.sheet_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'no_regex_var'):
            config_tab.no_regex_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'numeric_filter_enabled'):
            config_tab.numeric_filter_enabled.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'numeric_column_var'):
            config_tab.numeric_column_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'numeric_operator_var'):
            config_tab.numeric_operator_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'numeric_value_var'):
            config_tab.numeric_value_var.trace_add("write", lambda *args: self.update_command_display())
        if hasattr(config_tab, 'sheet_var'):
            config_tab.sheet_var.trace_add("write", lambda *args: self.update_command_display())

        # Set up callback for column changes
        if hasattr(config_tab, 'set_on_columns_changed'):
            config_tab.set_on_columns_changed(lambda: self.update_command_display())

        # Initial update
        self.update_command_display()
    
    def set_main_gui(self, main_gui):
        """
        Set the reference to the main GUI
        
        Args:
            main_gui: Reference to the main GUI instance
        """
        self.main_gui = main_gui
    
    def clear_log(self):
        """
        Clear the log text
        """
        self.log_text.config(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.config(state=tk.DISABLED)
        self.log_message(self.translations["log_cleared"] if self.translations else "Protokoll gelöscht")
        self.log_message(self.translations["ready_for_execution"] if self.translations else "Excel Filter bereit zur Ausführung")

    def save_log(self):
        """
        Save the log content to a file
        """
        try:
            from tkinter import filedialog
            import datetime

            # Generate default filename with timestamp
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            default_filename = f"excel_filter_log_{timestamp}.txt"

            # Ask user for save location
            file_path = filedialog.asksaveasfilename(
                defaultextension=".txt",
                filetypes=[("Textdateien", "*.txt"), ("Alle Dateien", "*.*")],
                initialfile=default_filename,
                title="Protokoll speichern"
            )

            if file_path:
                # Get log content
                log_content = self.log_text.get(1.0, tk.END).strip()

                # Add header with timestamp
                header = f"Excel Filter Protokoll - {datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')}\n"
                header += "=" * 50 + "\n\n"

                # Write to file
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(header + log_content)

                self.log_message(self.translations["log_saved"].format(file=file_path) if self.translations else f"💾 Protokoll gespeichert: {file_path}")

        except Exception as e:
            self.log_message(f"❌ Fehler beim Speichern des Protokolls: {e}")

    def start_execution(self):
        """
        Start execution - show progress bar and update status
        """
        self.is_executing = True
        self.status_var.set("⚡ " + (self.translations["execution_running"] if self.translations else "Läuft..."))
        self.progress_var.set(0.0)
        self.progress_bar.pack(side=tk.RIGHT, padx=(int(8 * self.scale_factor), 0))
        self.execute_button.config(state=tk.DISABLED, text="⏳ " + (self.translations["waiting"] if self.translations else "WARTEN..."))
        self.log_message(self.translations["execution_started"] if self.translations else "▶️ Ausführung gestartet")

    def update_progress(self, value, message=None):
        """
        Update progress bar and optionally log a message

        Args:
            value: Progress value (0-100)
            message: Optional message to log
        """
        self.progress_var.set(value)
        if message:
            self.log_message(message)

    def finish_execution(self, success=True):
        """
        Finish execution - hide progress bar and update status
        """
        self.is_executing = False
        self.progress_var.set(100.0)

        if success:
            self.status_var.set("✅ Fertig")
            self.log_message(self.translations["execution_completed"] if self.translations else "✅ Ausführung erfolgreich abgeschlossen")
        else:
            self.status_var.set("❌ Fehler")
            self.log_message(self.translations["execution_failed"] if self.translations else "❌ Ausführung mit Fehlern beendet")

        # Hide progress bar after a short delay
        self.frame.after(2000, lambda: self.progress_bar.pack_forget())

        # Re-enable execute button
        self.execute_button.config(state=tk.NORMAL, text="🚀 " + (self.translations["execute_button"] if self.translations else "AUSFÜHREN"))

    def get_frame(self):
        """
        Get the frame for this tab

        Returns:
            The frame containing all widgets
        """
        return self.frame
