#!/usr/bin/env python

# Origin: https://github.com/drbild/json2yaml (commit df499b6)
# Requires packages python-yaml and python-docopt
#
# Copyright 2015 David R. Bild
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

"""
Usage:
    yaml2json (--version|--help)
    yaml2json [-i <indent>] [<yaml_file>] [<json_file>]

Arguments:
    -i, --indent=INDENT  Number of spaces to indent [default: 4]
    <yaml_file>          The input file containing the YAML to convert. If not
                         specified, reads from stdin.
    <json_file>          The output file to which to write the converted JSON. If
                         not specified, writes to stdout.
"""

import sys, os
import json, yaml
import docopt

from collections import OrderedDict
from yaml import MappingNode

__version__ = "1.1.2-epi"

sys.tracebacklimit = 0

# Configure PyYaml to create ordered dicts
# using code taken from yaml/contructor.py

def flatten_ordered_mapping(loader, node):
    merge = []
    index = 0
    while index < len(node.value):
	key_node, value_node = node.value[index]
	if key_node.tag == u'tag:yaml.org,2002:merge':
	    del node.value[index]
	    if isinstance(value_node, MappingNode):
		flatten_ordered_mapping(loader, value_node)
		merge.extend(value_node.value)
	    elif isinstance(value_node, SequenceNode):
		submerge = []
		for subnode in value_node.value:
		    if not isinstance(subnode, MappingNode):
			raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping for merging, but found %s" % subnode.id, subnode.start_mark)
		    flatten_ordered_mapping(loader, subnode)
		    submerge.append(subnode.value)
		submerge.reverse()
		for value in submerge:
		    merge.extend(value)
	    else:
		raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping or list of mappings for merging, but found %s" % value_node.id, value_node.start_mark)

	elif key_node.tag == u'tag:yaml.org,2002:value':
	    key_node.tag = u'tag:yaml.org,2002:str'
	    index += 1
	else:
	    index += 1

	if merge:
	    for val in merge:
		node.value.insert(index, val)
		index += 1
	    merge = []

def construct_ordered_mapping(loader, node, deep=False):
    if isinstance(node, MappingNode):
        flatten_ordered_mapping(loader, node)
    return OrderedDict(loader.construct_pairs(node, deep))

def construct_yaml_ordered_map(loader, node, deep=False):
    data = OrderedDict()
    yield data
    value = construct_ordered_mapping(loader, node, deep)
    data.update(value)

yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_yaml_ordered_map)

# Multipurpose open
def safeopen(name, mode='r', buffering=1):
    if isinstance(name, file):
        return name
    elif name == '-':
        return sys.stdin
    else:
        return open(name, mode, buffering)

# Convert from YAML to JSON
def convert(yaml_file, json_file, indent):
    loaded_yaml = yaml.load(yaml_file)
    json.dump(loaded_yaml, json_file, separators=(',',': '), indent=indent)
    json_file.write('\n')

if __name__ == '__main__':
    args = docopt.docopt(
        __doc__,
        version="version "+__version__
    )

    yaml_arg   = args.get('<yaml_file>') or sys.stdin
    json_arg   = args.get('<json_file>') or sys.stdout
    indent_arg = int(args.get('--indent'))

    with safeopen(yaml_arg, 'r') as yaml_file:
        with safeopen(json_arg, 'w') as json_file:
            convert(yaml_file, json_file, indent=indent_arg)
