# This file is part of the Coral project.
# Please read the copyright notice in the LICENSE file.

import os
import time

import qt
from coral import log

logger=log.getLogger("iconcache")

import coral.configuration

config=coral.configuration.getCoralConfiguration()


# number of seconds that should pass before we look for a missing icon
# again
MISSING_ICON_SEARCH_INTERVAL = 10.0 

__iconCache={}


def __fixPath(s,metamodel=""):
    ip = config.dGet(["Coral","install_path"])

    from coral.modeler.coralmodeler import CoralModeler
    extensions = CoralModeler.getInstance().getExtensionPaths()
        
    head,tail = os.path.split(s)
    if os.path.isabs(s):
        trials = [s]
    elif head: # head!="" means we have a folder component
        trials = [os.path.join(ip,"coral","addins",metamodel,s),
                  os.path.join(config.dGet(["Coral","user_home"]),".coral",
                               "coral","addins",metamodel,s)]
        for ext in extensions:
            trials.append(os.path.join(ext, metamodel, s))
        
    else:
        if metamodel:
            coralicondir = os.path.join(ip,"coral","addins",metamodel,"icons")
        else:
            coralicondir = os.path.join(ip,"coral","modeler","icons")
        trials = [os.path.join(coralicondir,s)]
        
        for ext in extensions:
            trials.append(os.path.join(ext, metamodel, "icons", s))
            
    return trials

def getIcon(name,metamodel=""):
    global __iconCache

    if (metamodel,name) in __iconCache:
        entry = __iconCache.get((metamodel,name))
        if not entry[0].isNull() and os.access(entry[1],os.R_OK) and os.stat(entry[1])[9]<entry[2]:
            return entry[0]
        if entry[0].isNull() and time.time()-entry[2]<MISSING_ICON_SEARCH_INTERVAL:
            return entry[0]

    trials=__fixPath(name+".png",metamodel)
    for fn in trials:
        if not os.path.isfile(fn):
            #logger.info("coral.modeler.iconcache.getIcon: Bad trial on " + fn + " skipping")
            continue
        icon=qt.QPixmap(fn)
        __iconCache[(metamodel,name)]=(icon,fn,int(time.time()))
        return icon 
    if name=="nosuchicon":
        logger.error("coral.modeler.iconcache.getIcon: I cannot find any icon")
        assert(0)
    else:
        logger.info("coral.modeler.iconcache.getIcon: icon not found: "+name)
        #icon=getIcon("nosuchicon")
        icon = qt.QPixmap() # a null icon
        __iconCache[(metamodel,name)]=(icon,fn,int(time.time()))
    return icon

