import importlib
import pkgutil
import sys

from collections import OrderedDict

from inselect.lib.metadata import MetadataTemplate
from inselect.lib.utils import debug_print

_library = None


def library():
    """Returns a list of MetadataTemplate instances
    """
    global _library
    if not _library:
        _library = _load_library()
    return _library

def _load_library():
    # Import everything inselect.lib.templates that has a 'template' name
    # that is an instance of MetadataTemplate.
    # Returns an instance of OrderedDict with items sorted by key.
    try:
        templates = importlib.import_module('.lib.templates', 'inselect')
    except ImportError,e:
        debug_print(e)
    else:
        library = {}
        for loader, name, is_pkg in pkgutil.iter_modules(templates.__path__):
            try:
                pkg = importlib.import_module('{0}.{1}'.format(templates.__name__, name))
            except ImportError,e:
                debug_print(u'Error importing [{0}]: [{1}]'.format(name, e))
            else:
                template = getattr(pkg, 'template', None)
                if isinstance(template, MetadataTemplate):
                    debug_print('Loaded MetadataTemplate from [{0}]'.format(name))
                    # TODO Raise if duplicated name
                    library[template.name] = template
                else:
                    msg = u'Not an instance of MetadataTemplate [{0}]'
                    debug_print(msg.format(name))

        return OrderedDict(sorted(library.iteritems()))

@@ -173,41 +173,425 @@
 nt%0A%0A
-_library = None%0A%0A%0Adef library():%0A
+from inselect.lib.templates import dwc, price%0A%0A%0Aif True:%0A    _library = %7B%7D%0A    for template in %5Bp.template for p in (dwc, price)%5D:%0A        _library%5Btemplate.name%5D = template%0A    _library = OrderedDict(sorted(_library.iteritems()))%0A%0A    def library():%0A        return _library%0Aelse:%0A    # More flexible solution that breaks with frozen build on OS X using%0A    # PyInstaller%0A%0A    _library = None%0A%0A    def library():%0A    
     
@@ -638,16 +638,20 @@
 stances%0A
+    
     %22%22%22%0A
@@ -654,16 +654,20 @@
 %22%22%22%0A    
+ 
+   
 global _
@@ -678,16 +678,20 @@
 ary%0A    
+ 
+   
 if not _
@@ -699,32 +699,36 @@
 ibrary:%0A        
+ 
+   
 _library = _load
@@ -738,16 +738,20 @@
 brary()%0A
+    
     retu
@@ -763,16 +763,20 @@
 ibrary%0A%0A
+    
 def _loa
@@ -784,24 +784,28 @@
 _library():%0A
+    
     # Import
@@ -870,16 +870,20 @@
 ame%0A    
+ 
+   
 # that i
@@ -917,16 +917,20 @@
 mplate.%0A
+    
     # Re
@@ -988,25 +988,16 @@
 by key.%0A
-    try:%0A
         
@@ -1033,16 +1033,24 @@
 module('
+inselect
 .lib.tem
@@ -1060,80 +1060,9 @@
 tes'
-, 'inselect')%0A    except ImportError,e:%0A        debug_print(e)%0A    else:
+)
 %0A   

Fix metadata template import on OS X