#! /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

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)
            -h or --help  ... Print this message and exit.
        """

    # ===== command line parser
    try:
        opts, args = getopt.gnu_getopt( sys.argv[1:], "hvw", ["help", "viewer", "workflow"] )
        type = "program"
        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 not args:
            usage()
            sys.exit( 1 )
            
    except getopt.GetoptError:
            print usage()
            sys.exit( 1 )
    
    for file in args :
      print "Processing file %s..." % (str(file))
      try:
          val = Validator(type, file)
          val.run()
          if val.valOk:
              print "%s validates." % str(file)
              for re in val.rngErrors:
                  print " - %s" % re
          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.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))
