#!/usr/bin/env python
import sys
import os
import optparse
import sqlite3
import mpsconfig


def process_options(argv):
    """
    Return parsed command-line options found in the list of
    arguments, `argv`, or ``sys.argv[1:]`` if `argv` is `None`.
    """
    
    if argv is None:
        argv = sys.argv[1:]
    
    usage   = """Usage: %prog DATABASE EXPORT_TYPE... [options]
    
DATABASE                SQLite3 file containing MPS data
EXPORT_TYPE             One or more of the following types:
                            -s, --substitution      Substitution file
                            -i, --include           Channel mapping header file
                            -n, --state_notation    State notation program
                            -c, --csv               CSV files
                            -w, --www               HTML file
                            -e, --edm               EDM files
                            -d, --dump              Dump database to text file
                            -l, --latex             LaTeX Device/fault checklist"""
                
    version = "%prog 1.0"
    parser = optparse.OptionParser(usage=usage, version=version)

    parser.add_option("-v", "--verbose",           action="store_true",  dest="verbose",            help="print verbose output")

    parser.add_option("-s", "--substitutions",     action="store_true",  dest="export_sub",          help=optparse.SUPPRESS_HELP)
    parser.add_option("-i", "--include",           action="store_true",  dest="export_include",      help=optparse.SUPPRESS_HELP)
    parser.add_option("-n", "--state_notation",    action="store_true",  dest="export_snl",          help=optparse.SUPPRESS_HELP)
    parser.add_option("-c", "--csv",               action="store_true",  dest="export_csv",          help=optparse.SUPPRESS_HELP)
    parser.add_option("-w", "--www",               action="store_true",  dest="export_www",          help=optparse.SUPPRESS_HELP)
    parser.add_option("-e", "--edm",               action="store_true",  dest="export_edm",          help=optparse.SUPPRESS_HELP)
    parser.add_option("-d", "--dump",              action="store_true",  dest="export_dump",         help=optparse.SUPPRESS_HELP)
    parser.add_option("-l", "--latex",             action="store_true",  dest="export_latex",        help=optparse.SUPPRESS_HELP)
    
    group = optparse.OptionGroup(parser, "File Export Paths", "Use the following options to set destinations of exported files.")
    group.add_option("-S", "--substitutions_dir",   action="store", type="string", dest="subdir",       metavar="FILE", help="substitutions destination directory")
    group.add_option("-I", "--include_path",        action="store", type="string", dest="includepath",  metavar="FILE", help="include file path")
    group.add_option("-N", "--state_notation_path", action="store", type="string", dest="snlpath",      metavar="FILE", help="state notation program path")
    group.add_option("-C", "--csv_path",            action="store", type="string", dest="csvpath",      metavar="PATH", help="CSV destination directory")
    group.add_option("-W", "--www_path",            action="store", type="string", dest="wwwpath",      metavar="PATH", help="HTML file path")
    group.add_option("-E", "--edm_dir",             action="store", type="string", dest="edmpath",      metavar="PATH", help="EDM destination directory")
    group.add_option("-D", "--dump_path",           action="store", type="string", dest="dumppath",     metavar="FILE", help="Dump file path")
    group.add_option("-L", "--latex_path",          action="store", type="string", dest="latexpath",    metavar="FILE", help="LaTeX file path")
    parser.add_option_group(group)

    group = optparse.OptionGroup(parser, "LaTeX Options", "Use the following options to set destinations of exported files.")
    group.add_option("-b", "--embedlatex",      action="store_true",  dest="embed_latex",                        help="Export a LaTeX file that can be included in other documents")
    group.add_option("-r", "--latexrev",        action="store", type="string", dest="latex_rev",  metavar="REV", help="Document revision")
    parser.add_option_group(group)

    # Defaults
    parser.set_defaults(verbose        = False,
                        export_sub     = False,
                        export_include = False,
                        export_snl     = False,
                        export_csv     = False,
                        export_www     = False,
                        export_edm     = False,
                        export_dump    = False,
                        export_latex   = False,
                        embed_latex    = False,
                        latex_rev      = '')

    # Parse arguments
    (options, args) = parser.parse_args(argv)


    # Check if argument count
    has_at_least_one_export_type = (options.export_sub     or
                                    options.export_include or
                                    options.export_snl     or
                                    options.export_csv     or
                                    options.export_www     or
                                    options.export_edm     or
                                    options.export_dump    or
                                    options.export_latex)

    if (len(args) != 1) or (not has_at_least_one_export_type):
        parser.error("incorrect number of arguments")
    
    # Paths
    options.dbfile = os.path.normcase(args[0])
    dbbase, dbext = os.path.splitext(options.dbfile)
    dbdir = os.path.dirname(options.dbfile)

    options.substitutions_path = os.path.normcase( options.subdir      or dbdir                  )
    options.include_path       = os.path.normcase( options.includepath or dbbase + ".h"          )
    options.snl_path           = os.path.normcase( options.snlpath     or dbbase + ".stt"        )
    options.csv_path           = os.path.normcase( options.csvpath     or dbdir                  )
    options.www_path           = os.path.normcase( options.wwwpath     or dbdir                  )
    options.edm_path           = os.path.normcase( options.edmpath     or dbdir                  )
    options.dump_path          = os.path.normcase( options.dumppath    or dbbase + ".dump.txt"   )
    options.latex_path         = os.path.normcase( options.latexpath   or dbbase + ".tex"        )

    return options 


def main(argv=None):
    options = process_options(argv)
    
    dbfile = options.dbfile
    
    # Check if the dbfile exists
    if not os.path.isfile(dbfile):
        sys.stderr.write('Error: database "%s" does not exist\n' % dbfile)
        return 1

    if options.export_csv: mpsconfig.csv.export(dbfile, options.csv_path, options.verbose)
    if options.export_www: mpsconfig.html.export(dbfile, options.www_path, options.verbose)
    if options.export_dump: mpsconfig.dump.export(dbfile, options.dump_path, options.verbose)

    if (options.export_sub or options.export_include or options.export_snl or options.export_edm or options.export_latex):
        # Connect to database
        connection = sqlite3.connect(dbfile)
        connection.row_factory = sqlite3.Row
        cursor = connection.cursor()
            
        if options.export_sub: mpsconfig.substitution.export(cursor, options.substitutions_path, options.verbose)
        if options.export_include: mpsconfig.include.export(cursor, options.include_path, options.verbose)
        if options.export_snl: mpsconfig.snl.export(cursor, options.snl_path, options.verbose)
        if options.export_edm: mpsconfig.edm.export(cursor, options.edm_path, options.verbose)
        if options.export_latex: mpsconfig.latex.export(cursor, options.latex_path, options.latex_rev, options.embed_latex, options.verbose)
    
        connection.close()
    
    return 0


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



