"""
WSGI config for jocondelab project.

This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.

Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.

"""
import os, sys, site

# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "jocondelab.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jocondelab.settings")

# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)

def application(environ, start_response):

    global g_env_set, _application
    
    if 'g_env_set' not in globals() or not g_env_set:
    
        prev_sys_path = list(sys.path)
    
        sys.path.append(environ['PROJECT_PATH'])
        for path in environ.get('PYTHON_PATH', "").split(os.pathsep):
            if path:
                site.addsitedir(path) #@UndefinedVariable
    
        new_sys_path = [] 
        for item in list(sys.path): 
            if item not in prev_sys_path and item not in new_sys_path: 
                new_sys_path.append(item) 
                sys.path.remove(item)
        sys.path[:0] = new_sys_path

        from django.core.wsgi import get_wsgi_application
        _application = get_wsgi_application()

        g_env_set = True 


    if environ.get('PYDEV_DEBUG', "False").lower() in ["true", "1", "t"]:
        import pydevd #@UnresolvedImport
        pydevd.settrace(suspend=False)

    return _application(environ, start_response)
