# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
import base64
import hashlib
import json
import os

import click

from anaconda_enterprise.cli.internal import yaml

ERROR_ = click.style('ERROR', fg='red')


@click.command(name='spark-config')
@click.option('--config',
              multiple=True,
              type=(str, str),
              help="Config Tuple: (path in project, local path)")
@click.option('--output',
              type=str,
              help="Output YAML",
              default="anaconda-config-files-secret.yaml")
def main(config, output):
    """Manage configuration files for the user Docker image

       This command manages a special Kubernetes secret used by AE5 to
       customize the user Docker image by inserting configuration files
       upon startup. Historically, this command was called "spark-config"
       because of its use to configure connections to Spark clusters.
       Because of its wider utility, it can now be called "site-config" as well.
    """

    files_dict = {}
    for rp, lp in config:
        if not os.path.exists(lp):
            click.echo('Error: invalid local path {0}.'.format(lp))
            return
        else:
            with open(lp, 'rb') as f:
                data = f.read()
            files_dict[rp] = data

    yaml_config = make_config(files_dict)

    click.echo("Writing secret data to %s with the following paths: " % output)
    click.echo("\t%s " % '\n\t'.join(files_dict.keys()))

    with open(output, 'w') as f:
        f.write(yaml_config)

    click.echo("Completed...\nPlease upload secret to Kubernetes:\n"
               ">>> sudo kubectl replace -f %s " % output)


def _encode_str(data):
    try:
        return str(base64.b64encode(data), encoding='utf-8')
    except Exception:
        return str(base64.b64encode(data)).encode('UTF-8')


def make_config(files_dict):
    files_data = {
        hashlib.md5(path.encode('utf8')).hexdigest(): _encode_str(value)
        for (path, value) in files_dict.items()
    }
    manifest = {
        hashlib.md5(path.encode('utf8')).hexdigest(): path
        for path in files_dict
    }
    files_data['anaconda_manifest'] = _encode_str(
        json.dumps(manifest).encode('utf8'))
    return yaml.dump({
        'apiVersion': 'v1',
        'metadata': {
            'name': 'anaconda-config-files'
        },
        'data': files_data,
        'kind': 'Secret',
        'type': 'Opaque'
    })
