#! /usr/bin/python3
# -*- coding: utf-8 -*-

"""Get a creole variable value.
"""

import sys
import argparse

from creole.client import CreoleClient

from pyeole import scriptargs
from pyeole.log import init_logging
from pyeole.encode import normalize

_RETURN_VALUES = """Multiple values are separated with NEWLINE character '\\n',
or SPACE character if several variables are displayed."""

parser = argparse.ArgumentParser(description="Get creole variable",
                                 epilog=_RETURN_VALUES,
                                 parents=[scriptargs.logging()])

parser.add_argument('variable', nargs='?',
                    help="Nom de variable creole")
parser.add_argument('default', nargs='?',
                    help="Valeur par défaut si la variable n’existe pas")

incompatible_options = parser.add_mutually_exclusive_group()

incompatible_options.add_argument('--groups', action="store_true", default=False,
                    help="Liste les groupes de conteneurs")

incompatible_options.add_argument('--list', action="store_true", default=False,
                    help="Liste l'ensemble des variables creole")

incompatible_options.add_argument('--reload', action="store_true", default=False,
                    help="Recharge toute la configuration creole")

incompatible_options.add_argument('--reload-eol', action="store_true", default=False,
                    help="Recharge les valeurs de configuration creole")

options = parser.parse_args()

if options.verbose:
    # 'info' is outputed to stdout
    options.log_level = 'warning'
if options.debug:
    options.log_level = 'debug'

def output(value, strip_master=False):
    """
    formatage de l'affichage
    """
    if isinstance(value, list):
        #FIXME: ['val1', None, 'val2']
        for val in value:
            if isinstance(val, dict):
                sys.stderr.write('{}\n'.format(val['err']))
            else:
                sys.stdout.write('{}\n'.format(val))
    elif isinstance(value, dict):
        # in case several keys/values are returned
        list_keys = list(value.keys())
        list_keys.sort()
        for var in list_keys:
            values = value[var]
            if isinstance(values, list):
                values_ = ''
                for val in values:
                    if val and not isinstance(val, dict):
                        values_ += " {}".format(val)
                values = values_
            elif values is None:
                values = ''
            else:
                values = '{}'.format(values)
            if strip_master:
                varname = var.split('.')[-1]
            else:
                varname = var
            sys.stdout.write('{}="{}"\n'.format(varname, values.strip()))
    elif value is None or value == '':
        sys.stdout.write('\n')
    else:
        sys.stdout.write('{0}\n'.format(value))
    #return ret.rstrip('\n')

def main():
    """Setup environnment and run templatisation.
    """

    try:
        log = init_logging(level=options.log_level)
        client = CreoleClient()
        var = options.variable
        if options.groups:
            output(client.get_groups())
        elif options.list:
            output(client.get_creole(), True)
        elif options.reload:
            client.reload_config()
        elif options.reload_eol:
            client.reload_eol()
        elif not var:
            raise Exception("Veuillez spécifier un nom de variable Creole")
        else:
            if options.default is not None:
                kwargs = {'default':options.default}
            else:
                kwargs = {}
            if '.' in var:
                output(client.get(var))
            else:
                output(client.get_creole(var, **kwargs))

    except Exception as err:
        if options.debug:
            log.debug(normalize(err), exc_info=True)
        else:
            log.error(normalize(err))
        sys.exit(1)

    sys.exit(0)

if __name__ == '__main__':
    main()

