import logging
import os
from orangescape.model.server.Context import getApplication
import appconfig as config
from orangescape.model.server.Constants import EDITOR, INBOX, WORKTOP
from Cheetah.Template import Template
from orangescape.model.server.util.TemplateUtil import Context,Helper,Metadata,HttpRequest

""" Directory where the application jstls reside """
if config.env==config.SL:
    staticJstlPath = ''
    templatePath = 'templates'
    application_static_path=''
    common_static_path=''
    process_module_package = "TemplateUtil.%sPortlet"
elif config.env==config.ENTERPRISE:
    staticJstlPath = os.path.dirname(__file__).split('wsgiapp')[0]
    templatePath = os.path.join(staticJstlPath,'wsgiapp','orangescape','templates')
    application_static_path='/'+getApplication().getSheetId()
    common_static_path='/'+config.COMMON_FOLDER_NAME+'/'+config.VERSION
    portlet_module_package = "orangescape.model.server.util.TemplateUtil.%sPortlet"
elif config.env == config.AZURE:
    staticJstlPath = os.path.join(os.path.dirname(__file__),'orangescape')
    templatePath = os.path.join(staticJstlPath,'templates')
    common_static_path = application_static_path='/orangescape'
    portlet_module_package = "orangescape.model.server.util.TemplateUtil.%sPortlet"
else:
    staticJstlPath = os.path.join(os.path.dirname(__file__),'orangescape')
    templatePath = os.path.join(staticJstlPath,'templates')
    application_static_path=''
    common_static_path=''
    portlet_module_package = "orangescape.model.server.util.TemplateUtil.%sPortlet"

commonTemplateDict = {  'application_static_path' : application_static_path,
                        'common_static_path' : common_static_path,
                        'templatePath':templatePath,
                        'staticJstlPath':staticJstlPath,
                    }

def renderTemplate(templateName, templateDict, controller=None):
    try:
        templateDict.update(commonTemplateDict)
        if controller:
            templateDict['context'] = Context(controller.getSession())
            templateDict['metadata'] = Metadata(controller.getSession())
            templateDict['httprequest'] = HttpRequest(controller.request)
        if  not templateDict.__contains__('helper'):
            templateDict['helper'] = Helper()
        templateFile = os.path.join(templatePath,templateName)

#        from Cheetah.Compiler import Compiler
#        output = Compiler(file=templateFile, moduleName="test", mainClassName="TestCompile")
#        logging.info(str(output))

        template=Template(file=templateFile, searchList=[templateDict])
        return template.__str__()
    except:
        raise

def renderLayout(controller, typeName, jsonUrl, jstlPath, templateName, formName=None, filter="{}"):
    from orangescape.model.server.util.ServerUtil import _get_class
    jstlPath = os.path.join(os.sep,"static","jstl",jstlPath)
    portlet =  _get_class(portlet_module_package%typeName)(controller, typeName+"001", jsonUrl, jstlPath, formName, filter)

    templateDict = { 'portlet':portlet }
    return renderTemplate(templateName, templateDict, controller)


def renderWSDL(location,sheetMetadataName,paramDict,actions,relationShipDict):
    templateDict = {
                    'location':location,
                    'sheetMetadataName':sheetMetadataName,
                    'paramDict':paramDict,
                    'actions':actions,
                    'relationShipDict':relationShipDict
                    }
    return renderTemplate('wsdl.mako', templateDict)

def renderSoapResponse(metadataName,operation,sheet, params):
    templateDict = {
                    'sheet':sheet,
                    'params':params,
                    'metadataName':metadataName,
                    'operation':operation
                    }
    return renderTemplate('soapResponse.mako', templateDict)

def renderSoapFault(errorMsg):
    templateDict = {'errorMsg':errorMsg}
    return renderTemplate('soapFault.mako', templateDict)

def renderUploadPage(templatePath, url):
    templateDict = {'url':url}
    return renderTemplate(templatePath, templateDict)
