# -*- coding: utf-8 -*-
import sys
import glob

ENABLE_ADDONS = True

# This stores a list of paths where the addons can be found
try:
    ADDONS_ROOTS
except NameError:
    ADDONS_ROOTS = []

# Appending the '<projectdir>/addons/' into the ADDONS_ROOTS list
ADDONS_ROOTS.append(os.path.abspath(os.path.join(TX_ROOT, 'addons')))

# Making sure have have a list of non-duplicated paths
ADDONS_ROOTS = list(set(ADDONS_ROOTS))

# Subset of INSTALLED_APPS containing only addons without ADDONS_PREFIX
ADDONS = []

# Disabled addons are described in this file
# You can use './manage.py addons' to enable and disable addons
ADDONS_DISABLED_CONF = "disabled.conf"

# In ADDONS_DISABLED_CONF file there should be only one var ADDONS_DISABLED
ADDONS_DISABLED = []

# Made sure we add the path into the PYTHONPATH in the correct order.
ADDONS_ROOTS.reverse()

# This piece of code scans ADDONS_ROOTS and register all found folders as
# Django applications.
for ADDONS_ROOT in ADDONS_ROOTS:
    # Checking for disabled addons
    file = os.path.abspath(os.path.join(ADDONS_ROOT, ADDONS_DISABLED_CONF))
    if os.path.isfile(file):
        execfile(file)

    # Lets add the ADDONS_ROOT path into the system PYTHONPATH.
    if not ADDONS_ROOT in sys.path:
        sys.path.insert(0, ADDONS_ROOT)

    for dir in sorted(os.listdir(ADDONS_ROOT)):
        if not dir in ADDONS_DISABLED and \
        os.path.isdir(os.path.join(ADDONS_ROOT, dir)) and \
        os.path.isfile(os.path.join(ADDONS_ROOT, dir, "__init__.py")):
                if dir in ADDONS:
                    raise Exception("The addon '%s' is present in more " \
                                    "than one ADDONS_ROOT path." % dir)
                ADDONS.append(dir)
                if not dir in INSTALLED_APPS:
                    INSTALLED_APPS.append(dir)

                # Add addons' locale/ to the LOCALE_PATHS
                if "LOCALE_PATHS" in vars():
                    if not isinstance( LOCALE_PATHS, tuple):
                        LOCALE_PATHS = LOCALE_PATHS,
                    LOCALE_PATHS += os.path.join(ADDONS_ROOT, dir, 'locale/'),

                # Load settings/*.conf for each addon
                confs = os.path.join(ADDONS_ROOT, dir, 'settings', '*.conf')
                conffiles = glob.glob(confs)
                conffiles.sort()
                for f in conffiles:
                    execfile(os.path.abspath(f))

