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

from __future__ import print_function

import argparse
import logging
import os
import sys
import yaml

# Note the eval requires this!
import yaml_utilities
from yaml_utilities import R13, B64, Vault

from yaml_utilities import version, get_section_path, get_parameter_path


_description = """This small utility insert or replace a parameter value from a
configuration file. At this time, only the yaml format is supported."""

_epilog = """
Example(s):
    %(script)s -h                          - To provide this help
    %(script)s -P name config.yml          - To return the value of name var
    %(script)s -S user -P name config.yml  - Same with a section
    """ % {
        'script': os.path.basename(sys.argv[0]),
    }

# ----------------------------------------------------------------------
# SUPPORT FUNCTIONS
#


def get_new_data(data, path, value, typed_value=False):
    assert type(path) is list
    assert len(path) >= 1

    new_data = data
    ptr = new_data
    for k in path[:-1]:
        if k not in ptr.keys():
            ptr[k] = {}
        ptr = ptr[k]

    if typed_value:
        ptr[path[-1]] = eval(value)
    else:
        ptr[path[-1]] = str(value)

    return new_data


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(
        '-D', '--default-value',     # --default-value='' works, -D '' doesn't!
        default=None,
        help='Default value if not found',
        required=False,
    )
    parser.add_argument(
        '-e', '--environment',
        action='count',
        default=0,
        help='Environmnet variables override those provided',
        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(
        '-P', '--parameter',
        help='Parameter to extract',
        required=False,
    )
    parser.add_argument(
        '-S', '--section',
        help='Section of the parameter',
        required=False,
    )
    parser.add_argument(
        '-s', '--spaced',
        action='store_true',
        default=False,
        help='Use space to separate values in list/dict',
        required=False,
    )
    parser.add_argument(
        '-t', '--typed-value',
        action='store_true',
        default=False,
        help='Value has a type',
        required=False,
    )
    parser.add_argument(
        '-v', '--version',
        action='store_true',
        default=False,
        help='Returns the version',
        required=False,
    )
    parser.add_argument(
        '-V', '--value',
        default='None',
        help='Value to insert',
        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
    parameter = args.parameter
    spaced = args.spaced
    typed_value = args.typed_value
    value = args.value
    yaml_files = args.yaml_files
    data = dict()

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

    if spaced:
        input_separator = ' '

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

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

    n_yaml_files = len(yaml_files)
    if n_yaml_files > 1:
        logging.error('No more than one YAMl file!')
        exit(1)
    elif n_yaml_files == 0:
        logging.debug('Reading from stdin')
        input_str = sys.stdin.read()
        data = yaml.load(input_str)
    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)

    path = section_path + parameter_path
    logging.debug('path=%s', path)

    new_data = get_new_data(data, path, value, typed_value)

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

    kwargs = {
        'allow_unicode': None,
        # canonical=True,               # Includes type
        'default_flow_style': False,
        # 'default_style': '"',            # Quote everything!
        'encoding': 'utf-8',
        'explicit_end': True,              # ...
        'explicit_start': True,            # ---
        'indent': None,
        'line_break': None,
        'width': None,
    }

    dump = yaml.dump(data, **kwargs)

    if output_file is not None:
        with open(output_file, 'w') as f:
            print(dump, end='', file=f)
    else:
        print(dump)

main()
