#!/usr/bin/python

# need to do some path manipulations
import os

names = {} 
nameValues = {}

destination_dir = os.getenv( 'XSD_DEST_DIR', '/mbari/LRAUV/xsd' )

outfile = open( os.path.normpath( destination_dir + '/Units.xsd'), 'w' )
outfile.write( '<?xml version="1.0" encoding="UTF-8"?>\n' )
outfile.write( '<schema targetNamespace="Tethys/Units"\n' )
outfile.write( '    elementFormDefault="qualified"\n' )
outfile.write( '    xmlns="http://www.w3.org/2001/XMLSchema"\n' ) 
outfile.write( '    xmlns:Units="Tethys/Units"\n' ) 
outfile.write( '    xmlns:Tethys="Tethys">\n' )
outfile.write( '\n' )
outfile.write( '    <import namespace="Tethys" schemaLocation="http://okeanids.mbari.org/tethys/Xml/Tethys.xsd"/>\n' )

# we are using regular expression matching
import re
pattern = re.compile('[\s]*const[\s]+(?:Base)?Unit[\s]+Units::([\w_]+)[\s]*[\(][\s]*\"([^\"]+)\"[\s]*,[\s]*\"([^\"]+)\"')
patternWithBaseUnit = re.compile('[\s]*const[\s]+Unit[\s]+Units::[\w_]+[\s]*[\(][\s]*\"[^\"]+\"[\s]*,[\s]*\"[^\"]+\"[\s]*,[\s]*([^\s^,^\)]+)')
commentPattern = re.compile('[\s]*////[\s]*(.+)')

infile = open( os.path.normpath("../Source/units/Units.cpp"))
for line in infile.readlines():
    matches = pattern.match(line)
    if matches:
        outfile.write( '    <element' )
        outfile.write( ' id="' + matches.group(1) + '"' )
        outfile.write( ' name="' + matches.group(2) + '"' )
        outfile.write( ' substitutionGroup="Tethys:Unit" type="Tethys:UnitType">\n' )
        outfile.write( '        <annotation>\n' )
        outfile.write( '            <appinfo source="abbreviation">' + matches.group(3) + '</appinfo>\n' )
        matchesWithBaseUnit = patternWithBaseUnit.match(line)
        if matchesWithBaseUnit:
            baseUnit = matchesWithBaseUnit.group(1)
            if baseUnit != 'UCHAR1' and baseUnit != 'FLOAT2' and baseUnit != 'FLOAT3' and baseUnit != 'INT4' and baseUnit != 'FLOAT4' and baseUnit != 'DOUBLE4' and baseUnit != 'DOUBLE6' and baseUnit != 'DOUBLE8':
                outfile.write( '            <appinfo source="baseUnit">' + baseUnit + '</appinfo>\n' )
        outfile.write( '        </annotation>\n' )
        outfile.write( '    </element>\n' )
    else:
        matches = commentPattern.match(line)
        if matches:
            outfile.write( '\n' )
            outfile.write( '    <!-- ' + matches.group(1) + ' -->\n' )

infile.close()

outfile.write( '\n' )
outfile.write( '</schema>' )
outfile.close()    