#!/usr/bin/env python
#
# vim:ts=4:sw=4:expandtab
#
######################################################################

from __future__ import print_function

import argparse
import json
import logging
import os
import sys
import yaml

from yaml_utilities import get_section_path, version

_description = """This small utility transform a yaml file in another format
"""

_epilog = """
Example(s):
    %(script)s -h                             - To provide this help
    %(script)s -F json config.yml             - Transform the whole file
    %(script)s -F json -S users config.yml    - Same with a section
    """ % {
        'script': os.path.basename(sys.argv[0]),
    }


def main():
    parser = argparse.ArgumentParser(
        description=_description,
        epilog=_epilog,
        formatter_class=argparse.RawTextHelpFormatter,
    )
    parser.add_argument(
        '-d', '--debug',
        action='store_true',
        default=False,
        help='Debug mode',
        required=False,
    )
    parser.add_argument(
        '-I', '--input-separator',
        default='/',
        help='Separator used in input parameters',
        required=False,
    )
    parser.add_argument(
        '-O', '--output-file',
        help='Output file',
        required=False,
    )
    parser.add_argument(
        '-F', '--format',
        default='json',
        help='Destination format',
        required=False,
    )
    parser.add_argument(
        '-S', '--section',
        help='Section of the parameter',
        required=False,
    )
    parser.add_argument(
        '-v', '--version',
        action='store_true',
        default=False,
        help='Return version',
        required=False,
    )
    parser.add_argument(
        '-y', '--yaml-stdin',
        action='count',
        default=0,
        help='YAML on Stdin overrides provided vars',
        required=False,
    )
    parser.add_argument(
        'yaml_files',
        help='YAML files to read',
        nargs='*',
    )
    args = parser.parse_args()
    debug = args.debug
    input_separator = args.input_separator
    output_file = args.output_file
    section = args.section
    format = args.format
    yaml_files = args.yaml_files
    data = dict()

    if debug > 0:
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('debug=%s', args.debug)

    logging.debug('yaml_files=%s', yaml_files)
    logging.debug('format=%s', format)
    logging.debug('input_separator=%s', input_separator)
    logging.debug('output_file=%s', output_file)
    logging.debug('section=%s', section)

    if args.version is True:
        print(version)
        return

    n_yaml_files = len(yaml_files)
    if n_yaml_files == 0:
        logging.error('You must provide a YAML file')
        exit(1)
    elif n_yaml_files > 1:
        logging.error('Only one YAML file please!')
        exit(2)
    else:
        with open(yaml_files[0], 'r') as f:
            data = yaml.load(f)

    logging.debug('data=%s', data)

    section_path = get_section_path(section, input_separator)
    # parameter_path = get_parameter_path(parameter, input_separator)

    steps = section_path  # + parameter_path

    ptr = data
    for step in steps:
        ptr = ptr[step]

    kwargs = {
        # 'default_flow_style': False,
        'allow_nan': True,
        'check_circular': True,
        'encoding': 'UTF-8',
        'ensure_ascii': True,        # All non-ASCII char are escaped in output
        # 'canonical': False,
        # 'width': 50,
        'indent': 4,                 # Pretty print with that indent level
        # 'default_style': '',
        'separators': (',', ': '),
        'skipkeys': False,
        'sort_keys': True,
    }

    if output_file is not None:
        with open(output_file, 'w') as f:
            print(json.dumps(ptr, **kwargs), file=f)
    else:
        # print(json.dumps(ptr))
        print(json.dumps(ptr, **kwargs))


main()
