# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2017 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
import logging
from contextlib import contextmanager
from pprint import pprint

import click

from anaconda_enterprise.cli.config import ConfigurationError
from anaconda_enterprise.cli.internal import yaml


@contextmanager
def ignore_warnings():
    logging.disable(logging.WARNING)
    yield
    logging.disable(logging.NOTSET)


@click.group(name='config')
def main():
    """Manage configuration"""


@main.command()
@click.pass_obj
@click.argument('key')
@click.argument('value')
def set(config_manager, key, value):
    try:
        conf_yaml = yaml.load(value)
        new_conf = config_manager.new_config(key, conf_yaml)
    except ConfigurationError as e:
        raise click.ClickException("%s" % e)

    # this reads configuration file using load_yaml_file, which uses load_yaml_string
    # which runs the update function, which will print the warning on screen again
    # since it was shown during the loading of the config, so we ignore warnings.
    with ignore_warnings():
        user_conf = config_manager.get_user_config()

    new_conf = config_manager.merge_configs(user_conf, new_conf)
    config_manager.dump(new_conf)


@main.command()
@click.pass_obj
@click.argument('key')
def get(config_manager, key):
    try:
        value = config_manager[key]
    except KeyError:
        raise click.ClickException("Option '{key}' is not set".format(key=key))
    else:
        pprint(value)


@main.command()
@click.pass_obj
def view(config_manager):
    for path_ in config_manager.find_config_files():
        with open(path_) as fd:
            config_str = fd.read()
            click.echo('{}:'.format(path_))
            click.echo(config_str)
            click.echo()
