from Metadata import ApplicationModel
import datetime
from pickleUtil import unpickle
import appconfig as config

if config.env==config.SL:
    application_path = ""
else:
    import os
    application_path=os.path.join(os.path.dirname(__file__).split('model')[0],'application')

if config.pickle:
    context = unpickle(application_path,"Application.pck")
    formMapping = unpickle(application_path,'formmapping.pck')
    actionMapping = unpickle(application_path,'actionmapping.pck')
    importMapping = unpickle(application_path, 'importmapping.pck')
else:
    from orangescape.application.Application import Application as context
    from orangescape.application.formmapping import formMapping
    from orangescape.application.actionmapping import actionMapping
    from orangescape.application.importmapping import importMapping

#    from orangescape.tests.functional.server.test.Application import Application as context
#    from orangescape.tests.functional.server.test.formmapping import formMapping
#    from orangescape.tests.functional.server.test.actionmapping import actionMapping
#    from orangescape.tests.functional.server.test.importmapping import importMapping

startTime = datetime.datetime.now()
application = ApplicationModel(context, formMapping, actionMapping)
globalInstance = None

def getApplication():
    global application
    return application

def getGlobalInstance(session, sync=False):
    global globalInstance
    if not globalInstance or sync:
        application =getApplication()
        globalSheet = application.getSheetMetadata('Global')
        globalInstance=session.getIfExists('global', globalSheet)
    return globalInstance
