# -*- coding: utf-8 -*-

"""
This program validates an xml invoice file against the xsd schema version 1.2

Needs:

 Virtualenv with python 2.7 and pyxb package installed
 See README file for details on the fa12 module generation with pyxbgen

Params:

 xml file name  (required)
 output file name for results, if the validation fails. if omitted the output is directed to stdout

Exit code: 0=ok; 1=file is not valid, see the results

"""

import fa12
import pyxb
import sys

xmlfile = sys.argv[1]
if len(sys.argv) > 2:
    ofile = open(sys.argv[2], "w")
else:
    ofile = sys.stdout

xml = open(xmlfile).read()
try:
    fattura = fa12.CreateFromDocument(xml)
    sys.exit(0)
except pyxb.exceptions_.ValidationError as e:
    ofile.write(e.details())
    sys.exit(1)
