# -*- coding: utf-8 -*-
"""
Theme Support Module for Jet Guide Kodi Addon

Provides dynamic theme switching functionality with:
- Dark theme (default)
- Light theme  
- Custom user-defined colors
"""

import xbmc
import xbmcaddon
import xbmcgui

# Default theme definitions
# Format: (primary_color, secondary_color, background_color, text_color, focused_color, header_bg, button_bg, accent_color)

THEMES = {
    'dark': {
        'name': 'Dark',
        'colors': {
            'primary': 'FFFFD700',        # Gold - primary accent
            'secondary': 'FFFFFFFF',     # White - secondary text
            'background': 'CC000000',    # Black with transparency
            'text': 'FFFFFFFF',           # White text
            'focused': 'FFFFD700',        # Gold focused
            'header_bg': 'FF1A1A1A',      # Dark gray header
            'button_bg': 'FF2D2D2D',      # Button background
            'button_focus': 'FF404040',   # Button focus
            'panel_bg': 'CC000000',       # Panel background
            'border': 'FF404040',         # Border color
            'highlight': 'FFFFD700',      # Highlight color
            'disabled': 'FF808080',       # Disabled text
            'success': 'FF00FF00',        # Green for success
            'error': 'FFFF0000',          # Red for errors
            'info': 'FF00BFFF',           # Blue for info
        }
    },
    'light': {
        'name': 'Light',
        'colors': {
            'primary': 'FF0066CC',        # Blue - primary accent
            'secondary': 'FF333333',      # Dark gray - secondary
            'background': 'FFF5F5F5',     # Light gray background
            'text': 'FF000000',           # Black text
            'focused': 'FF0066CC',        # Blue focused
            'header_bg': 'FFE0E0E0',      # Light gray header
            'button_bg': 'FFFFFFFF',      # White button background
            'button_focus': 'FFE8E8E8',  # Light gray focus
            'panel_bg': 'FFFFFFFF',       # White panel
            'border': 'FFCCCCCC',         # Light border
            'highlight': 'FF0066CC',      # Blue highlight
            'disabled': 'FF999999',       # Gray disabled
            'success': 'FF008000',        # Dark green
            'error': 'FFCC0000',          # Dark red
            'info': 'FF0066CC',           # Blue
        }
    },
    'custom': {
        'name': 'Custom',
        'colors': {}  # Will be populated from settings
    }
}


def get_addon():
    """Get addon instance."""
    return xbmcaddon.Addon('plugin.video.jet_guide')


def get_theme_name():
    """Get the current theme name from settings."""
    try:
        addon = get_addon()
        theme = addon.getSetting('theme_choice')
        if not theme:
            theme = 'dark'  # Default to dark
        # Convert to lowercase for consistency
        theme = theme.lower()
        xbmc.log(f'Jet Guide: Theme setting value = "{theme}"', xbmc.LOGDEBUG)
        return theme
    except Exception as e:
        xbmc.log(f'Jet Guide: Error getting theme: {str(e)}', xbmc.LOGERROR)
        return 'dark'


def get_theme_colors(theme_name=None):
    """
    Get the color palette for a specific theme.
    
    Args:
        theme_name: Name of theme ('dark', 'light', 'custom'). If None, uses current setting.
    
    Returns:
        Dictionary of color values
    """
    if theme_name is None:
        theme_name = get_theme_name()
    
    if theme_name == 'custom':
        return get_custom_colors()
    
    if theme_name in THEMES:
        return THEMES[theme_name]['colors'].copy()
    
    # Default to dark theme
    return THEMES['dark']['colors'].copy()


def get_custom_colors():
    """
    Get custom colors from settings.
    Returns dictionary with custom color values or defaults if not set.
    """
    try:
        addon = get_addon()
        
        # Get custom color settings (stored as hex strings without alpha)
        custom_colors = {
            'primary': addon.getSetting('custom_primary_color') or 'FFD700',
            'secondary': addon.getSetting('custom_secondary_color') or 'FFFFFF',
            'background': addon.getSetting('custom_background_color') or '000000',
            'text': addon.getSetting('custom_text_color') or 'FFFFFF',
            'focused': addon.getSetting('custom_focused_color') or 'FFD700',
            'header_bg': addon.getSetting('custom_header_bg') or '1A1A1A',
            'button_bg': addon.getSetting('custom_button_bg') or '2D2D2D',
            'button_focus': addon.getSetting('custom_button_focus') or '404040',
            'panel_bg': addon.getSetting('custom_panel_bg') or '000000',
            'border': addon.getSetting('custom_border') or '404040',
            'highlight': addon.getSetting('custom_highlight') or 'FFD700',
            'disabled': addon.getSetting('custom_disabled') or '808080',
            'success': addon.getSetting('custom_success') or '00FF00',
            'error': addon.getSetting('custom_error') or 'FF0000',
            'info': addon.getSetting('custom_info') or '00BFFF',
        }
        
        # Add full alpha (FF) to colors that don't have it
        for key, value in custom_colors.items():
            if len(value) == 6:  # RGB only, add full alpha
                custom_colors[key] = 'FF' + value.upper()
        
        return custom_colors
        
    except Exception as e:
        xbmc.log(f'Jet Guide: Error getting custom colors: {str(e)}', xbmc.LOGERROR)
        return THEMES['dark']['colors'].copy()


def apply_theme_to_window(window):
    """
    Apply current theme colors to a Kodi window as properties.
    
    This allows skin XML files to use $INFO[Window.Property(theme_color)] 
    to dynamically change colors based on the selected theme.
    
    Args:
        window: xbmcgui.Window instance
    """
    try:
        colors = get_theme_colors()
        theme_name = get_theme_name()
        
        # Apply all theme colors as window properties
        for key, value in colors.items():
            property_name = f'theme_{key}'
            window.setProperty(property_name, value)
        
        # Also set the theme name for conditional logic
        window.setProperty('theme_name', theme_name)
        
        xbmc.log(f'Jet Guide: Applied {theme_name} theme - primary={colors.get("primary", "N/A")}, background={colors.get("background", "N/A")}', xbmc.LOGDEBUG)
        
    except Exception as e:
        xbmc.log(f'Jet Guide: Error applying theme: {str(e)}', xbmc.LOGERROR)


def get_color_value(color_key):
    """
    Get a specific color value by key.
    
    Args:
        color_key: Key for the color (primary, secondary, background, etc.)
    
    Returns:
        Color value as hex string (e.g., 'FFFFD700')
    """
    colors = get_theme_colors()
    return colors.get(color_key, 'FFFFFFFF')


def get_available_themes():
    """
    Get list of available themes with their display names.
    
    Returns:
        List of tuples: [(theme_id, display_name), ...]
    """
    return [
        ('dark', 'Dark'),
        ('light', 'Light'),
        ('custom', 'Custom Colors')
    ]


def reset_to_default(theme_name='dark'):
    """
    Reset a theme to its default colors.
    
    Args:
        theme_name: Name of theme to reset
    """
    try:
        addon = get_addon()
        
        if theme_name == 'custom':
            # Clear custom color settings
            custom_settings = [
                'custom_primary_color', 'custom_secondary_color', 
                'custom_background_color', 'custom_text_color',
                'custom_focused_color', 'custom_header_bg',
                'custom_button_bg', 'custom_button_focus',
                'custom_panel_bg', 'custom_border',
                'custom_highlight', 'custom_disabled',
                'custom_success', 'custom_error', 'custom_info'
            ]
            for setting in custom_settings:
                addon.setSetting(setting, '')
                
        xbmc.log(f'Jet Guide: Reset {theme_name} theme to defaults', xbmc.LOGINFO)
        
    except Exception as e:
        xbmc.log(f'Jet Guide: Error resetting theme: {str(e)}', xbmc.LOGERROR)


def refresh_theme():
    """
    Refresh the current theme by reloading the active window.
    This allows theme changes to apply immediately.
    """
    try:
        xbmc.executebuiltin('SendClick(13002)')
        xbmc.sleep(100)
        xbmc.executebuiltin('Dialog.Close(all)')
        xbmc.sleep(100)
        xbmc.executebuiltin('ActivateWindow(13002)')
    except Exception as e:
        xbmc.log(f'Jet Guide: Error refreshing theme: {str(e)}', xbmc.LOGERROR)
