#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)

__license__   = 'GPL v3'
__copyright__ = '2011, Grant Drake <grant.drake@gmail.com>'
__docformat__ = 'restructuredtext en'



# Global definition of our plugin name. Used for common functions that require this.
PLUGIN_NAME = None

# Global definition of our plugin resources. Used to share between the xxxAction and xxxBase
# classes if you need any zip images to be displayed on the configuration dialog.
PLUGIN_RESOURCES = {}

THEME_COLOR = ['', 'dark', 'light']

def get_theme_color():
    if calibre_version > (5, 90) and 'user-any' in QIcon.themeName():
        return THEME_COLOR[1] if QApplication.instance().is_dark_theme else THEME_COLOR[2]
    return THEME_COLOR[0]

def get_icon_themed(icon_name, theme_color=None):
    theme_color = theme_color if theme_color != None else get_theme_color()
    return icon_name.replace('/', '/'+theme_color+'/', 1).replace('//', '/')


def set_plugin_icon_resources(name, plugin_path, resources=[]):
    '''
    Set our global store of plugin name and icon resources for sharing between
    the InterfaceAction class which reads them and the ConfigWidget
    if needed for use on the customization dialog for this plugin.
    '''
    resources = resources or []
    
    global PLUGIN_NAME, PLUGIN_RESOURCES
    PLUGIN_NAME = name
    
    if plugin_path is None:
        raise ValueError('This plugin was not loaded from a ZIP file')
    ans = {}
    from calibre.utils.zipfile import ZipFile
    with ZipFile(plugin_path, 'r') as zf:
        lst = zf.namelist()
        for name in names:
            for color in THEME_COLOR:
                themed = get_icon_themed(name, color)
                if themed in lst:
                    ans[themed] = zf.read(themed)
    
    PLUGIN_RESOURCES.update(ans)

def get_icon(icon_name=None):
    '''
    Retrieve a QIcon for the named image from the zip file if it exists,
    or if not then from Calibre's image cache.
    '''
    def themed_icon(icon_name):
        if calibre_version < (5, 90):
            return QIcon(I(icon_name))
        else:
            return QIcon.ic(icon_name)
    
    if icon_name:
        pixmap = get_pixmap(icon_name)
        if pixmap is None:
            # Look in Calibre's cache for the icon
            return themed_icon(icon_name)
        else:
            return QIcon(pixmap)
    return QIcon()

def get_pixmap(icon_name):
    '''
    Retrieve a QPixmap for the named image
    Any icons belonging to the plugin must be prefixed with 'images/'
    '''
    
    if not icon_name.startswith('images/'):
        # We know this is definitely not an icon belonging to this plugin
        pixmap = QPixmap()
        pixmap.load(I(icon_name))
        return pixmap
    
    # Build the icon_name according to the theme of the OS or Qt
    icon_themed = get_icon_themed(icon_name)
    
    # Check to see whether the icon exists as a Calibre resource
    # This will enable skinning if the user stores icons within a folder like:
    # ...\AppData\Roaming\calibre\resources\images\Plugin Name\
    def get_from_local(name):
        local_images_dir = get_local_images_dir(PLUGIN_NAME)
        local_image_path = os.path.join(local_images_dir, name.replace('images/', ''))
        if os.path.exists(local_image_path):
            pxm = QPixmap()
            pxm.load(local_image_path)
            return pxm
        return None
    
    if PLUGIN_NAME:
        pixmap = get_from_local(icon_themed)
        if not pixmap:
            pixmap = get_from_local(icon_name)
        if pixmap:
            return pixmap
    
    ##
    # As we did not find an icon elsewhere, look within our zip resources
    global PLUGIN_RESOURCES
    def get_from_resources(name):
        if name in PLUGIN_RESOURCES:
            pxm = QPixmap()
            pxm.loadFromData(PLUGIN_RESOURCES[name])
            return pxm
        return None
    
    pixmap = get_from_resources(icon_themed)
    if not pixmap:
        pixmap = get_from_resources(icon_name)
    if pixmap:
        return pixmap
    
    return None

def get_local_images_dir(subfolder=None):
    '''
    Returns a path to the user's local resources/images folder
    If a subfolder name parameter is specified, appends this to the path
    '''
    images_dir = os.path.join(config_dir, 'resources/images')
    if subfolder:
        images_dir = os.path.join(images_dir, subfolder.replace('/','-'))
    
    if iswindows:
        images_dir = os.path.normpath(images_dir)
    return images_dir

