#! /usr/bin/env python
#############################################################
#                                                           #
#   Author: Herve Menager                                   #
#   Organization:'Biological Software and Databases' Group, #
#                Institut Pasteur, Paris.                   #
#   Distributed under GPLv2 Licence. Please refer to the    #
#   COPYING.LIB document.                                   #
#                                                           #
#############################################################
import mb_cgi
from Mobyle.DataInputsIndex import DataInputsIndex
from  Mobyle.Classes.DataType import DataTypeFactory
from Mobyle.MobyleError import MobyleError

df = DataTypeFactory()

def getDataType(dataTypeClass,dataTypeSuperClass):
    if dataTypeSuperClass:
        dt = df.newDataType(dataTypeSuperClass,dataTypeClass)
    else:
        try:
            dt = df.newDataType(dataTypeClass)
        except MobyleError , err:
            return None
    if dt.isMultiple():
        return dt.dataType
    else:
        return dt
        

def process( self ):
    bc = self.cfg.getDatabanksConfig()
    pdi = DataInputsIndex("program")
    wdi = DataInputsIndex("workflow")
    vdi = DataInputsIndex("viewer")
    datatypes = {}
    dataInputsList = pdi.getList().values() + vdi.getList().values()
    for parameter in dataInputsList:
        if not(datatypes.has_key(parameter.get('dataTypeClass'))):
            datatypes[parameter.get('dataTypeClass')]={}
            dt = getDataType(parameter.get('dataTypeClass'),parameter.get('dataTypeSuperClass'))
            if dt:
                datatypes[parameter.get('dataTypeClass')]['ancestorTypes']=dt.ancestors
    program_workflow_inputs = dict(pdi.getList().items() + wdi.getList().items())
    for key,input in program_workflow_inputs.items():
        dt = getDataType(input.get('dataTypeClass'),input.get('dataTypeSuperClass'))
        if dt:
            input['dataTypeClass']=dt.name
    email_results =  not(self.cfg.mailResults()[0])
    self.jsonMap = {'portal_name': self.cfg.portal_name(),
                    'email_results': email_results,
                    'simple_forms_active':self.cfg.simple_forms_active(),
                    'conversions':self.cfg.data_conversions(),
                    'banks': bc,
                    'program_workflow_inputs': program_workflow_inputs,
                    'viewer_inputs': vdi.getList(),
                    'datatypes':datatypes,
                    'htbase':'/'+self.cfg.portal_url(True)+"/"}

if __name__ == "__main__":
    mb_cgi.JSONCGI(processFunction=process,mime_type="application/javascript",wrapper="var portalProperties = %s;")