'''
Remove an object from Anaconda Cloud

example::

    anaconda remove sean/meta/1.2.0/meta.tar.gz

'''
from binstar_client.utils import get_server_api, parse_specs, \
    bool_input
from argparse import RawTextHelpFormatter
from binstar_client import errors

import logging
log = logging.getLogger('binstar.remove')

def main(args):

    aserver_api = get_server_api(args.token, args.site, args.log_level)

    for spec in args.specs:
        try:
            if spec._basename:
                msg = 'Are you sure you want to remove file %s ?' % (spec,)
                if args.force or bool_input(msg, False):
                    aserver_api.remove_dist(spec.user, spec.package, spec.version, spec.basename)
                else:
                    log.warn('Not removing file %s' % (spec))
            elif spec._version:
                msg = 'Are you sure you want to remove the package release %s ? (and all files under it?)' % (spec,)
                if args.force or bool_input(msg, False):
                    aserver_api.remove_release(spec.user, spec.package, spec.version)
                else:
                    log.warn('Not removing release %s' % (spec))
            elif spec._package:
                msg = 'Are you sure you want to remove the package %s ? (and all data with it?)' % (spec,)
                if args.force or bool_input(msg, False):
                    aserver_api.remove_package(spec.user, spec.package)
                else:
                    log.warn('Not removing release %s' % (spec))
            else:
                log.error('Invalid package specification: %s', spec)

        except errors.NotFound:
            if args.force:
                log.warn('', exc_info=True)
                continue
            else:
                raise


def add_parser(subparsers):

    parser = subparsers.add_parser('remove',
                                      help='Remove an object from Anaconda Cloud. Must refer to the formal package name as it appears in the URL of the package. Also use anaconda show <USERNAME> to see list of pacakge names. Example: anaconda remove continuumio/empty-example-notebook',
                                      description=__doc__, formatter_class=RawTextHelpFormatter)

    parser.add_argument('specs', help='Package written as <user>[/<package>[/<version>[/<filename>]]]', type=parse_specs, nargs='+')
    parser.add_argument('-f', '--force', help='Do not prompt removal', action='store_true')



    parser.set_defaults(main=main)
