#
#   PyGUI - Resources - Generic
#

import os
from Exceptions import ResourceNotFoundError

resource_path = []

def _add_file_path(file, up = 0):
    #print "GUI.Resources: Adding path for file", repr(file) ###
    dir = os.path.dirname(os.path.abspath(file))
    while up > 0:
        dir = os.path.dirname(dir)
        up -= 1
    resdir = os.path.join(dir, "Resources")
    if os.path.isdir(resdir):
        resource_path.insert(0, resdir)
    #print "...resource_path =", resource_path ###

def _add_module_path(module, up = 0):
    if hasattr(module, '__file__'):
        _add_file_path(module.__file__, up)

def lookup_resource(name, type = None):
    if type:
        name = "%s.%s" % (os.path.splitext(name)[0], type)
    relpath = os.path.join(*name.split("/"))
    for dir in resource_path:
        path = os.path.join(dir, relpath)
        if os.path.exists(path):
            return path
    return None

def find_resource(name, type = None):
    path = lookup_resource(name, type)
    if not path:
        raise ResourceNotFoundError(name)
    return path
