"""
System Tray functionality for AutoBackups application
Provides system tray icon with options to open browser and close application
"""

import threading
import webbrowser
import os
from pathlib import Path
import pystray
from PIL import Image
import logging


class SystemTrayManager:
    """Manages system tray icon and menu for AutoBackups"""

    def __init__(self, app_instance, host="127.0.0.1", port=5000):
        """
        Initialize system tray manager

        Args:
            app_instance: The main AutoBackups Flask application instance
            host: Web server host (default: 127.0.0.1)
            port: Web server port (default: 5000)
        """
        self.app_instance = app_instance
        self.host = host
        self.port = port
        self.icon = None
        self.logger = logging.getLogger(__name__)

        # Get icon path
        self.icon_path = self._get_icon_path()

    def _get_icon_path(self):
        """Get the path to the favicon.png icon"""
        current_dir = Path(__file__).parent.parent.parent
        icon_path = current_dir / "static" / "icons" / "favicon.png"

        if not icon_path.exists():
            self.logger.warning(f"Icon file not found at {icon_path}")
            return None

        return str(icon_path)

    def _load_icon_image(self):
        """Load the icon image from file"""
        if not self.icon_path:
            # Create a simple default icon if file not found
            return Image.new("RGB", (64, 64), color="blue")

        try:
            return Image.open(self.icon_path)
        except Exception as e:
            self.logger.error(f"Error loading icon image: {e}")
            # Return a simple default icon
            return Image.new("RGB", (64, 64), color="blue")

    def _open_browser(self, icon, item):
        """Open web browser to the application URL"""
        url = f"http://{self.host}:{self.port}"
        try:
            webbrowser.open(url)
            self.logger.info(f"Opened browser to {url}")
        except Exception as e:
            self.logger.error(f"Error opening browser: {e}")

    def _quit_application(self, icon, item):
        """Quit the application"""
        try:
            self.logger.info("Shutting down application from system tray")

            # Stop the scheduler if it exists
            if (
                self.app_instance
                and hasattr(self.app_instance, "scheduler")
                and self.app_instance.scheduler
            ):
                self.app_instance.scheduler.shutdown(wait=False)

            # Stop the system tray icon
            if self.icon:
                self.icon.stop()

            # Exit the application
            os._exit(0)

        except Exception as e:
            self.logger.error(f"Error during application shutdown: {e}")
            os._exit(1)

    def _show_status(self, icon, item):
        """Show application status (placeholder for future implementation)"""
        # This could show a status window or notification in the future
        self.logger.info("Status requested from system tray")

    def create_tray_icon(self):
        """Create and configure the system tray icon"""
        try:
            # Load the icon image
            image = self._load_icon_image()

            # Create menu items
            menu = pystray.Menu(
                pystray.MenuItem(
                    "Open AutoBackups",
                    self._open_browser,
                    # This will be the action when double-clicking the icon
                    default=True,
                ),
                pystray.MenuItem("Status", self._show_status),
                pystray.Menu.SEPARATOR,
                pystray.MenuItem("Exit", self._quit_application),
            )

            # Create the icon
            self.icon = pystray.Icon(
                "AutoBackups", image, "AutoBackups - Automatic Backup System", menu
            )

            self.logger.info("System tray icon created successfully")
            return self.icon

        except Exception as e:
            self.logger.error(f"Error creating system tray icon: {e}")
            return None

    def start_tray(self):
        """Start the system tray icon in a separate thread"""
        if not self.icon:
            self.icon = self.create_tray_icon()

        if self.icon:
            try:
                # Run the tray icon in a separate thread
                tray_thread = threading.Thread(target=self.icon.run, daemon=True)
                tray_thread.start()
                self.logger.info("System tray started successfully")
                return True
            except Exception as e:
                self.logger.error(f"Error starting system tray: {e}")
                return False

        return False

    def stop_tray(self):
        """Stop the system tray icon"""
        if self.icon:
            try:
                self.icon.stop()
                self.logger.info("System tray stopped")
            except Exception as e:
                self.logger.error(f"Error stopping system tray: {e}")
