#! /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.Registry import registry, DefNode, CategoryDef, ProgramDef, Registry
from Mobyle.ClassificationIndex import ClassificationIndex
from Mobyle.SearchIndex import SearchIndex
from Mobyle.DescriptionsIndex import DescriptionsIndex
import simplejson as json

def encode_registry(obj):
    if isinstance(obj, Registry):
        return {'categories': [encode_registry(c) for c in obj.getChildCategories()],
                'programs': [encode_registry(c) for c in obj.getChildServices()]
                }
    elif isinstance(obj, CategoryDef):
        return {'name':obj.name,
                'categories': [encode_registry(c) for c in obj.getChildCategories()],
                'programs': [encode_registry(c) for c in obj.getChildServices()]
                }
    elif isinstance(obj, ProgramDef):
        return {'name': obj.name, 
                'description': obj.description
                }
    else:
        return str(obj)


def process(self):
    searchString = self.request.getfirst('searchString',None)
    if searchString:
        si = SearchIndex("program")
        self.response['filterOn'] = 'true'
        si.filterRegistry(searchString.split(' '))
    classification = ClassificationIndex("program")
    DescriptionsIndex("program").fillRegistry()
    classification.buildRegistryCategories()
    self.jsonMap = registry
    self.encoder = encode_registry
      
if __name__ == "__main__":
    mb_cgi.JSONCGI(processFunction=process)