#!/usr/bin/python3
import yaml
from charmhelpers.core import hookenv
from jaascharm import (
    update_config_and_restart,
    update_status,
    HTTP_LISTEN_PORT,
)
from status import charm_status


def config_changed():
    config = hookenv.config()

    try:
        idps = yaml.safe_load(config['identity-providers'])
    except:
        hookenv.status_set(
            'blocked',
            'invalid YAML value for identity-providers config attribute',
        )
        return

    app_config = {
        # Keys that are not changed by charm config:
        'access-log': '/var/log/candid/access.log',
        'private-addr': hookenv.unit_private_ip(),
        'resource-path': '/srv/candid/service',

        # Keys that don't map one-to-one with the
        # charm configuration keys.
        'listen-address': ':{}'.format(HTTP_LISTEN_PORT),
        'identity-providers': idps,
    }
    # Location defaults to the public IP address (best we can do)
    # unless explicitly set.
    if config['location'] == '':
        app_config['location'] = 'http://{}:{}'.format(
            hookenv.unit_public_ip(),
            HTTP_LISTEN_PORT,
        )
    else:
        app_config['location'] = config['location']

    for key in [
        'admin-agent-public-key',
        'admin-password',
        'http-proxy',
        'logging-config',
        'no-proxy',
        'private-key',
        'public-key',
        'rendezvous-timeout',
    ]:
        app_config[key] = None if config[key] == '' else config[key]

    update_config_and_restart(app_config)


if __name__ == '__main__':
    config_changed()
    update_status(failed_status=charm_status)
