#!/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python
# -*- coding: UTF-8 -*-

'''
$RCSfile: grouping.py,v $
$Revision: 883 $
$Author: markus $
$Date: 2008-04-24 20:07:57 +0200 (Do, 24. Apr 2008) $
The BioCASE querytool
'''

import os, sys
# ***** include the biocase.lib directory in the python sys path for importing *****
execfile( os.path.abspath( os.path.join( os.path.dirname( __file__ ), os.pardir, os.pardir, 'lib', 'biocase', 'adjustpath.py' ) ))

from biocase.querytool.general import *


############################################################################################################
#
#   MAIN
#
#===========================================================================================================

tmpl = PageMacro('Content', PageMacro.DELMODE)
tmpl.load('Content', os.path.join(skinDir, 'grouping.html'))

# build a new filter object from form values
filterObj = createFilter(form, schemaObj)
log.info("FILTER OBJ: %s"%str(filterObj))

# generate the protocol
QG = QueryGenerator()
groupConcept = form['groupby'].value
protocolXML = QG.getScanProtocol(concept=schemaObj.getConcept(groupConcept).path, NS=schemaObj.NS, filterObj=filterObj)
log.info("QUERY PROTOCOL CREATED:\n%s"%escapeHtml(protocolXML))

# update template
tmpl['dsa'] = dsa
tmpl['schema'] = schema
tmpl['limit'] = str(schemaObj.limit)
if filterObj is not None:
    tmpl['filter'] = str(filterObj)
tmpl['filter_display'] = escapeHtml( str(filterObj).replace('_', ' ') )
tmpl['groupingCon'] = groupConcept
tmpl['groupby_options'] = getDropDownOptionHtml(vals=['---None---']+[c.label for c in schemaObj.concepts], default='---None---')
if wrapper_url is not None:
    tmpl['wrapper_url'] = wrapper_url

# query the wrapper
QD = QueryDispatcher()
try:
    recStatus = QD.sendQuery(wrapper_url, protocolXML, security_role=security_role)
    # wrapper results:
    valuelist = QD.getScanValues()
    log.debug("Value list returned from querydispatcher: %s"%str(valuelist))
    logDiagnostics(QD.getDiagnostics())
    # wrapper results:
    tmpl['hits'] = str(recStatus.count)
    valueTemplateList = [{'val':v} for v in valuelist]
    tmpl.expand('Content', 'grouplist', valueTemplateList)
except WrapperError, e:
    tmpl = PageMacro('Content', PageMacro.DELMODE)
    tmpl.load('Content', '_error.html')
    tmpl['dsa']=dsa
    tmpl['ErrorMessage']=e.msg


#
# print HTML !
#
printOverHTTP( tmpl )
