import os
import glob
import importlib
import logging

logger = logging.getLogger(__name__)

class UnknownFormatError(RuntimeError):
    pass


item_classes = []
supported_protocols = []


def constructor_exists(path):
    for klass in item_classes:
        if klass.applies(path):
            return True
    return False


def find_constructors(path, **kwargs):
    """Available constructors for a path.

    """
    applies = ((float(klass.applies(path, **kwargs)), klass) for klass in item_classes)
    contructors = list(sorted((c for c in applies if c[0] > 0.0), key=lambda c: (c[0], c[1].__name__)))
    logging.debug("For {0}, constructors found: {1}".format(path, contructors))
    return contructors


def find_best_constructor(path, **kwargs):
    constructors = find_constructors(path, **kwargs)
    if constructors:
        return find_constructors(path)[-1][1]
    else:
        return None


def 
(name, storage, path):
    """Try to create item using one of the registered constructors."""
    klass = find_best_constructor(path)
    if klass:
        return klass(storage, name, path)
    else:
        raise UnknownFormatError("Cannot interpret file %s" % path)


def register(klass):
    """Make this class available to storage for creating items.

    :type klass: type

    Works as decorator for both classes and functions.
    """
    item_classes.append(klass)
    logger.info("Registered item class %s." % klass.__name__)
    supported_protocols.extend(getattr(klass, "protocols", []))
    return klass


def _auto_import():
    """Automatically imports all modules from this directory."""
    for subdir in ["formats", "pseudoitems"]:
        py_files = glob.glob(os.path.join(os.path.dirname(__file__), subdir) +"/*.py")
        py_files = filter(lambda f: os.path.isfile(f) and not os.path.basename(f).startswith('_'),
                          py_files)
        modules = [os.path.basename(py_file[:-3]) for py_file in py_files]
        subpackage = importlib.import_module("." + subdir, __package__)

        for module_name in modules:
            try:
                importlib.import_module("." + module_name, subpackage.__name__)
            except Exception as i:
                logger.warning("Module %s could not be imported, reason: %s" % (module_name, i))
    from . import directory

_auto_import()



read_item