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

from anaconda_enterprise.cli.api import _list, create_client, pass_client


@click.group(name='channels')
@click.pass_context
def main(ctx):
    """Manage conda channels"""
    ctx.obj = create_client(ctx.obj)


def _list_channels(channels):
    _list(('Name', 'Updated (UTC)'), ('name', 'updated'),
          [c['attributes'] for c in channels])


@main.command()
@pass_client
def list(client):
    _list_channels(client.channels())


@main.command()
@click.argument('name')
@pass_client
def create(client, name):
    _list_channels([client.create_channel(name)])


def _get_namespace(group, user, role):
    if group:
        return group, 'groups'
    elif user:
        return user, 'users'
    elif role:
        return role, 'roles'
    else:
        return None, None


@main.command()
@click.argument('channel_name', metavar='channel')
@click.option('--group', help='Group to share with')
@click.option('--user', help='User to share with')
@click.option('--role', help='Role to share with')
@click.option('--remove',
              is_flag=True,
              default=False,
              help='Remove share for a given user, group, or role.')
@click.option('--level',
              help='The level of permission to grant to the shared channel',
              type=click.Choice([
                  'r',
                  'rw',
              ]),
              default='r')
@pass_client
def share(client, channel_name, group, user, role, remove, level):
    channel = client.get_channel(channel_name)
    if channel is None:
        click.echo('Error: invalid channel {0}.'.format(channel_name))
        return

    name, namespace = _get_namespace(group, user, role)
    if namespace is not None:
        if remove:
            client.remove_shared_channel(channel_name, name, namespace)
            click.echo('Channel sharing removed.')
        else:
            client.share_channel(channel, name, namespace, level)
            click.echo('Channel shared.')


@main.command()
@click.argument('channel_name', metavar='channel')
@pass_client
def delete(client, channel_name):
    channel = client.get_channel(channel_name)
    if channel is None:
        click.echo('Error: invalid channel {0}.'.format(channel_name))
        return

    client.delete_channel(channel)
    click.echo('Channel "{0}" deleted.'.format(channel_name))
