#!/usr/bin/env python
import sys
import os
import optparse
import textwrap
import mpslogic


def process_options(argv=sys.argv[1:]):
    long_usage = textwrap.dedent(
        '''
        Usage: %prog <mpl_file> <export_types> [options]
        
        <mpl_file>              Machine Protection Logic (.mpl) file
    
        Specify one or more of the following <export_types>
        
          -c, --ccode           C code
          -l, --latex           LaTeX documentation
          -r, --rst             reStructuredText documentation'''[1:]
    )
    short_usage = 'Usage: %prog <mpl_file> <export_types> [options]'
                
    version = '%prog 1.0'
    parser = optparse.OptionParser(usage=long_usage, version=version)

    parser.add_option('-c', '--ccode',   action='store_true',  dest='export_code',   help=optparse.SUPPRESS_HELP)
    parser.add_option('-l', '--latex',   action='store_true',  dest='export_latex',  help=optparse.SUPPRESS_HELP)
    parser.add_option('-r', '--rst',     action='store_true',  dest='export_rst',    help=optparse.SUPPRESS_HELP)
    
    group = optparse.OptionGroup(parser, 'File Export Paths', 'Set export destinations with the following options')
    group.add_option('-C', action='store',  type='string',  dest='code_path',   metavar='PATH',  help='Code file path')
    group.add_option('-L', action='store',  type='string',  dest='latex_path',  metavar='PATH',  help='LaTeX file path')
    group.add_option('-R', action='store',  type='string',  dest='rst_path',    metavar='PATH',  help='LaTeX file path')
    parser.add_option_group(group)

    group = optparse.OptionGroup(parser, 'LaTeX Options', 'Set LaTeX documentation properties with the following option')
    group.add_option('-i', '--latex_rev',   action='store',  type='string',  dest='latex_rev',   metavar='REV',   help='LaTeX document revision')
    parser.add_option_group(group)

    # Defaults
    parser.set_defaults(
        export_code  = False,
        export_latex = False,
        export_rst   = False,
        latex_rev    = '--',
        code_path    = sys.stdout,
        latex_path   = sys.stdout,
        rst_path     = sys.stdout,
    )

    # Parse arguments
    (options, args) = parser.parse_args(argv)
    parser.usage = short_usage
    
    if len(args) != 1:
        parser.error('incorrect number of arguments')

    if not (options.export_code or options.export_latex or options.export_rst):
        parser.error('must specify at least one of -c, -l, -r')

    # Paths
    options.mpl_path = os.path.normcase(args[0])
    dbbase, dbext  = os.path.splitext(options.mpl_path)

    # Check if the dbfile exists
    if not os.path.isfile(options.mpl_path):
        sys.stderr.write('Error: database "{0}" does not exist\n'.format(options.mpl_path))
        return 1

    return (options, args)


def main(argv=None):
    (options, args) = process_options(argv)

    logic = mpslogic.Logic(path=options.mpl_path)
    logic.revision = options.latex_rev

    if options.export_code:
        if options.code_path is not sys.stdout:
            with open(options.code_path, 'w') as f:
                logic.export_c_code(f)
        else:
            logic.export_c_code()

    if options.export_latex:
        if options.latex_path is not sys.stdout:
            with open(options.latex_path, 'w') as f:
                logic.export_latex(f)
        else:
            logic.export_latex()

    if options.export_rst:
        if options.rst_path is not sys.stdout:
            with open(options.rst_path, 'w') as f:
                logic.export_rst(f)
        else:
            logic.export_rst()
        
    return 0


if __name__ == '__main__':
    status = main()
    sys.exit(status)

