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

'''
$RCSfile: check_errors.cgi,v $
$Revision: 946 $
$Author: j.torre $
$Date: 2008-11-26 11:26:59 +0100 (Mi, 26. Nov 2008) $
The BioCASE TestingTool
'''

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

#Import some stuff-----------------------------------------
import cgitb; cgitb.enable()
import cgi
import string
import os, sys
import inspect as               _i
import os as                    _os
import os.path as               _p
import urllib
from xml.etree import ElementTree
import biocase.configuration
import logging, biocase.initlogs
biocase.initlogs.initWebappLogging()

# get config data
cfg=biocase.configuration.Cfg()

# Take parameters
form = cgi.FieldStorage()

#First query the wrapper with the XML sent
wrapper_url = cfg.getAccessPoint(form['dsa'].value)
protocolXML = form['search'].value

errors=[]

try:
  params = urllib.urlencode({'query': protocolXML, 'debug':form['debug'].value})
  source = urllib.urlopen(wrapper_url, params)
except:
  errors.append("Can't open wrapper URL %s" % wrapper_url)

# Use Elementtree to parse XML
try:
  for event, elem in ElementTree.iterparse(source):
    if elem.tag=='diagnostic' and elem.attrib.has_key('severity') and elem.attrib['severity']=="error":
      errors.append(elem.text)
      elem.clear()
except:
  errors.append("Can't parse wrapper response. Seems to be no valid XML")
  try:
    errors.append("RESPONSE:\n%s" % data)
  except:
    pass

#Print the headers	
print 'Content-Type: text/html; charset=UTF-8'
print # Blank line marking end of HTTP headers
print '''<html><body><link href="../resources/css/biocase.css" rel="stylesheet" type="text/css"></link>'''
if (len(errors)<1):
  print '<h2><font color="green">No Errors detected</font></h2><ul>'
else:
  print '<h2><font color="red">There are %i errors</font></h2><ul>' % len(errors)
  for e in errors:
    print "<li>%s</li>" % e
  print "</ul></h2>"
print "</body></html>"


