#!/usr/bin/env python

import sys
import types

from UploadFunctions import *
from UploadClasses import _Constants
from UploadClasses import _Schematron
from xml.dom.ext.reader import Sax2

# ===PROLOG START===
print "This script won't run as is -- it must be installed into another"
print "directory using Install.sh."
sys.exit(1)
# ===PROLOG END===

def Usage():
  print "Usage: " + sys.argv[0] + " uploadfile.xml [schematron.xml]"
  print ""
  print "This tool does a first-pass validation of the upload XML file "
  print "by applying schematron rules to it.  If not specified, the schematron "
  print "file is found by searching for a file protocols/PROJECT.schematron,"
  print "where PROJECT is the project name specified in the XML file."

OPT_verbose = False

args = sys.argv[:]
try:
  i = 1
  while i < len(args):
    if args[i] == "--verbose":
      OPT_verbose = True
      args = args[:i] + args[i+1:]
    else:
      i += 1
except:
  Usage()
  sys.exit(1)

if len(args) < 2 or len(args) > 3:
  Usage()
  sys.exit(1)

# Load the xml file
reader = Sax2.Reader()
XMLDoc = reader.fromUri(args[1])

protocolfile = None
if len(args) == 3:
  protocolfile = args[2]
else:
  # look for schematron file based on project name
  try:
    projectname = XPathEval('/FIPS/project/name',XMLDoc)[0].encode('ascii')
  except:
    print "ERROR: Can't find <project><name> element in XML file!\n"
    sys.exit(1)
  protocolfile = os.path.dirname(__file__) + '/protocols/' + projectname + '.schematron'
  if not os.path.isfile(protocolfile):
    print 'ERROR: Could not find protocol validation (schematron) file for project ' + projectname + ' (tried ' + protocolfile + ').'
    sys.exit(1)

# do validation
schematron = _Schematron(protocolfile)
reader = Sax2.Reader()

protocolErrs = []
numProtocolErrs = 0

phases = [ "FIPS", "FIPS GUI" ]
try:
  scannermanufacturer = XPathEval('/FIPS/scannerManufacturer',XMLDoc)[0].encode('ascii')
  phases.extend([ "FIPS (%s)" % scannermanufacturer, "FIPS GUI (%s)" % scannermanufacturer ])
except:
  protocolErrs.append(("***ERROR: Can't find <scannerManufacturer> element in XML file!***\n", None))
  numProtocolErrs += 1

for phase in phases:
  protocolErrs.append(("==== Phase: " + phase + "\n", None))
  [numerrs, errors] = schematron.applyToDoc(XMLDoc, '<internal>', phase)
  if numerrs < 0:
    print "Error applying Schematron file."
    sys.exit(1)
  numProtocolErrs += numerrs
  protocolErrs.extend(errors)

if numProtocolErrs == 0:
  print "No errors found!"
  sys.exit(0)

if numProtocolErrs == 1:
  print "There was " + str(numProtocolErrs) + " potential protocol error in the XML file."
else:
  print "There were " + str(numProtocolErrs) + " potential protocol errors in the XML file."
for errorentry in protocolErrs:
  (errMsg, contextnodes) = errorentry
  print errMsg,
  if OPT_verbose and type(contextnodes) == types.ListType:
    for ind in range(len(contextnodes)):
      print "context " + str(ind + 1) + ":"
      print xml2string(contextnodes[ind])
sys.exit(2)

