# -*- 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


def _list_indexes(indexes, action=None):
    _list(('Name', 'Updated (UTC)'), ('name', 'updated'),
          [c['attributes'] for c in indexes],
          action=action,
          what='index',
          plural='es')


@click.group(name='pypi_indexes')
@click.pass_context
def main(ctx):
    """Manage pypi indexes"""
    ctx.obj = create_client(ctx.obj)


@main.command()
@pass_client
def list(client):
    _list_indexes(client.pypi_indexes())


@main.command()
@click.argument('name')
@pass_client
def create(client, name):
    _list_indexes([client.create_pypi_index(name)], action='created')


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('pypi_index_name', metavar='pypi_index')
@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 PyPI index',
              type=click.Choice([
                  'r',
                  'rw',
              ]),
              default='r')
@pass_client
def share(client, pypi_index_name, group, user, role, remove, level):
    pypi_index = client.get_pypi_index(pypi_index_name)
    name, namespace = _get_namespace(group, user, role)
    if namespace is not None:
        if remove:
            acl = client.get_pypi_index_acl(pypi_index, name, namespace)
            client.delete_pypi_index_acl(acl)
            click.echo('Permission removed.')
        else:
            client.create_pypi_index_acl(pypi_index, name, namespace, level)
            click.echo(
                'Shared PyPI index {} with {} {} with {} permission.'.format(
                    pypi_index_name, namespace, name, level))


@main.command()
@click.argument('pypi_index_name', metavar='pypi_index')
@pass_client
def delete(client, pypi_index_name):
    pypi_index = client.get_pypi_index(pypi_index_name)
    client.delete_pypi_index(pypi_index)
    _list_indexes([pypi_index], action='deleted')
