#!/usr/bin/python
""" Utility functions for jsonwidget"""
import optparse
import sys

import jsonwidget.commands

from jsonwidget.jsontypes import schemaformat

if __name__ == "__main__":
    '''urwid-based image metadata editor'''
    usage = """\
usage: %prog command filename
  Valid commands:
    editserver:    launch a web server to edit a json file from a browser
    json2yaml:     convert a json file to yaml with comments pulled from schema
    schemagen:     create a schema from an example json file
    upgradeschema: create a version 2 schema from a version 1 schema
    validate:      validate a schema
    yaml2json:     convert a yaml file to json\
"""
    cmdparser = optparse.OptionParser(usage)
    cmdparser.disable_interspersed_args()
    (options, args) = cmdparser.parse_args()


    if len(args)<1:
        cmdparser.error("no command given")
    elif args[0] == 'upgradeschema':
        usage = """\
Create a version 2 schema from a version 1 schema
  usage: %prog upgradeschema oldschema\
"""
        subparser = optparse.OptionParser(usage=usage)
        (options, subargs) = subparser.parse_args(args[1:])
        if len(subargs)==1:
            jsonwidget.commands.upgrade_schema(subargs[0])
            sys.exit(0)
        elif len(subargs)<1:
            subparser.error("old schema file required")
        else:
            subparser.error("only one file at a time")
    elif args[0] == 'schemagen':
        usage = """\
Create a schema from an example json file
  usage: %prog schemagen [options] jsonfile\
"""
        subparser = optparse.OptionParser(usage=usage)
        versionhelp = "schema format version to use.  Default: %i" % \
                      schemaformat.version
        subparser.add_option("-v", "--version", dest="version", type="int",
                             default=schemaformat.version,
                             help=versionhelp)
        (options, subargs) = subparser.parse_args(args[1:])
        if len(subargs)==1:
            schemaobj = jsonwidget.generate_schema(subargs[0], 
                                                   version=options.version)
            print schemaobj.dumps()
            sys.exit(0)
        elif len(subargs)<1:
            subparser.error("jsonfile required")
        else:
            subparser.error("only one file at a time")
    elif args[0] == 'json2yaml':
        import jsonwidget.yamltools
        usage = """\
Convert a file from json to yaml, pulling in comments from the given schema if
one is provided.
  usage: %prog json2yaml [options] jsonfile\
"""
        subparser = optparse.OptionParser(usage=usage)
        schemahelp = "schema format version to use.  Default: None"
        subparser.add_option("-s", "--schema", dest="schema", type="str",
                             default=None,
                             help=schemahelp)
        (options, subargs) = subparser.parse_args(args[1:])

        if len(subargs)==1:
            schemafile = options.schema
            schemaobj = None

            if schemafile is None:
                schemaobj = jsonwidget.generate_schema(subargs[0])
            jsonobj = jsonwidget.jsonnode.JsonNode(filename=subargs[0], 
                                                   schemafile=schemafile,
                                                   schemanode=schemaobj)
            print jsonwidget.yamltools.jsonnode_to_yaml(jsonobj)
            sys.exit(0)
        elif len(subargs)<1:
            subparser.error("jsonfile required")
        else:
            subparser.error("only one file at a time")
    elif args[0] == 'yaml2json':
        import json
        import yaml

        usage = """\
Convert a file from yaml to json.
  usage: %prog json2yaml [options] jsonfile\
"""
        subparser = optparse.OptionParser(usage=usage)
        (options, subargs) = subparser.parse_args(args[1:])

        fp = open(subargs[0])
        foo = yaml.load(fp)
        fp.close()
        print json.dumps(foo, indent=4, sort_keys=True)

    elif args[0] == 'validate':
        import json
        import sys

        usage = """\
Validate a JSON file against a schema.
  usage: %prog validate [options] jsonfile\
"""
        schemafile = jsonwidget.find_system_schema("openschema.json")
        subparser = optparse.OptionParser(usage=usage)
        schemahelp = "schema format version to use.  Default: %s" % schemafile
        subparser.add_option("-s", "--schema", dest="schema", type="str",
                             default=schemafile,
                             help=schemahelp)
        (options, subargs) = subparser.parse_args(args[1:])
        if len(subargs)==1:
            try:
                jsonwidget.jsonnode.JsonNode(filename=subargs[0], 
                                             schemafile=options.schema)
                print "Valid file!  " + subargs[0] + \
                    " validates against " + options.schema
            except jsonwidget.jsonnode.JsonNodeError as inst:
                print str(inst)
                sys.exit(1)
        elif len(subargs)<1:
            subparser.error("jsonfile required")
        else:
            subparser.error("only one file at a time")
            
    elif args[0] == 'editserver':
        import json
        import sys
        from jsonwidget.server.wsgieditserver import start_server

        usage = """\
Launch a web server which serves a Javascript-based JSON editor for a single \
file.
  usage: %prog editserver [options] jsonfile\
"""

        schemafile = jsonwidget.find_system_schema("openschema.json")
        subparser = optparse.OptionParser(usage=usage)
        schemahelp = "schema format version to use.  Default: %s" % schemafile
        subparser.add_option("-s", "--schema", dest="schema", type="str",
                             default=schemafile,
                             help=schemahelp)
        (options, subargs) = subparser.parse_args(args[1:])

        if len(subargs)==1:
            start_server(jsonfile=subargs[0], schemafile=options.schema)
        elif len(subargs)<1:
            subparser.error("jsonfile required")
        else:
            subparser.error("only one file at a time")
    else:
        cmdparser.error(args[0] + ' is not a valid command.')
    
    




