#!/usr/bin/python
# Copyright (C) 2010 Samuel Abels.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
import sys, os
sys.path.insert(0, 'src')
from Gelatin             import __version__, generator
from optparse            import OptionParser
from Gelatin.parser      import Parser
from Gelatin.parser.util import error
from Gelatin.compiler    import SyntaxCompiler

usage  = '''%prog [options]'''
parser = OptionParser(usage = usage, version = __version__)
parser.add_option('--syntax', '-s',
                  dest    = 'syntax',
                  metavar = 'FILE',
                  default = None,
                  help    = '''
The file containing the syntax for parsing the input
''')
parser.add_option('--format', '-f',
                  dest    = 'format',
                  default = 'xml',
                  metavar = 'FORMAT',
                  help    = '''
The output format. Valid values are: xml json yaml none. Default is xml.
''')

if __name__ == '__main__':
    # Parse options.
    options, args = parser.parse_args(sys.argv)
    args.pop(0)

    if not options.syntax:
        parser.error('missing switch -s')
    if not os.path.exists(options.syntax):
        parser.error('no such file or directory: ' + options.syntax)
    if not os.path.isfile(options.syntax):
        parser.error('not a valid input file: ' + options.syntax)

    try:
        input_file = args[0]
    except:
        parser.error('missing input file')

    if options.format == 'xml' or options.format == 'none':
        builder = generator.Xml()
    elif options.format == 'json':
        builder = generator.Json()
    elif options.format == 'yaml':
        builder = generator.Yaml()
    else:
        parser.error('invalid output format: ' + options.format)

    gel     = open(options.syntax).read()
    input   = open(input_file).read()
    parser  = Parser()
    context = parser.parse(gel, SyntaxCompiler())
    context.parse(input, builder)
    if options.format != 'none':
        print builder.serialize()
