#! /usr/bin/env python
import os , sys, getopt

MOBYLEHOME = None
if os.environ.has_key('MOBYLEHOME'):
    MOBYLEHOME = os.environ['MOBYLEHOME']
if not MOBYLEHOME:
    sys.exit('MOBYLEHOME must be defined in your environment')

if ( MOBYLEHOME ) not in sys.path:
    sys.path.append( MOBYLEHOME )
if ( os.path.join( MOBYLEHOME , 'Src' ) ) not in sys.path:    
    sys.path.append( os.path.join( MOBYLEHOME , 'Src' ) )

from Mobyle.Validator import Validator
from Mobyle.Registry import registry
from Mobyle.DataTypeValidator import DataTypeValidator
dtv = DataTypeValidator()

if __name__ == '__main__':

    def usage():
        print """
        Usage: mobvalid [OPTION]... FILE... 
        Validate Mobyle service description files (program or viewer), each FILE being the path to the file.
    
        option:
            -w or --workflow    Validate a workflow
                              (Default validates a command line program)
            -v or --viewer    Validate a viewer
                              (Default validates a command line program)
            -j or --jing      Also run Jing to validate (gives more accurate error messages than the usual validation
                              mechanism)
                              (Requires java and that the jing jarfiles are located in MOBYLEHOME/Tools/validation/jing)
            -q or --quiet  ... Do not print any message if the file validates
            -h or --help  ... Print this message and exit.
        """

    
    # ===== command line parser
    try:
        opts, args = getopt.gnu_getopt( sys.argv[1:], "hvwtjq", ["help", "viewer", "workflow", "tutorial", "jing", "quiet"] )
        type = "program"
        useJing = False    
        beQuiet = False
        for option , value in opts:     
            if option in ( "-h", "--help" ):
                usage()
                sys.exit( 0 )
            if option in ( "-v", "--viewer"):
                print option
                type = "viewer"
            if option in ( "-w", "--workflow"):
                print option
                type = "workflow"
            if option in ( "-t", "--tutorial"):
                print option
                type = "tutorial"
            if option in ( "-j", "--jing"):
                useJing = True
            if option in ( "-q", "--quiet"):
                beQuiet = True
        if not args:
            usage()
            sys.exit( 1 )
            
    except getopt.GetoptError:
            usage()
            sys.exit( 1 )
    
    for file in args :
      if not(beQuiet):
          print "Processing file %s..." % (str(file))
      val = Validator(type, file,runRNG_Jing=useJing)
      val.run()
      try:
          if val.valOk:
              errors = dtv.validateDataTypes(docPath=file)
              if len(errors)!=0:
                  print "%s does NOT validate. Details follow:" % str(file)
                  print "* datatypes validation failed - errors detail:"
                  for error in errors:
                      print " - %s" % error
              elif not(beQuiet):
                  print "%s validates." % str(file)
          else:
              print "%s does NOT validate. Details follow:" % str(file)
          if val.runRNG and not(val.rngOk):
              print "* relax ng validation failed - errors detail:"
              for re in val.rngErrors:
                   print " - line %s, column %s: %s" % (re.line, re.column, re.message)
          if val.runRNG_Jing and not(val.rng_JingOk):
              print "* relax ng JING validation failed - errors detail:"
              for line in val.rng_JingErrors:
                   print "- %s" % (line)
          if val.runSCH and not(val.schOk):
              print "* schematron validation failed - errors detail:"
              for se in val.schErrors:
                  print " - %s" % se
      except Exception, e:
          print "Error processing file %s: %s" % (str(file), str(e))