#!/usr/bin/env python3
#
# (c) 2017 Fetal-Neonatal Neuroimaging & Developmental Science Center
#                   Boston Children's Hospital
#
#              http://childrenshospital.org/FNNDSC/
#                        dev@babyMRI.org
#

import sys
import os
from argparse import ArgumentParser

sys.path.insert(1, os.path.join(os.path.dirname(__file__), '..'))

from chrisstoreclient import client


parser = ArgumentParser(description='Manage plugins')
parser.add_argument('storeurl', help="Url of ChRIS store")
parser.add_argument('-u', '--username', help="Username for the ChRIS store")
parser.add_argument('-p', '--password', help="Password for the ChRIS store")
subparsers = parser.add_subparsers(dest='subparser_name', title='subcommands',
                                   description='valid subcommands',
                                   help='sub-command help')

# create the parser for the "list" command
parser_list = subparsers.add_parser('list', help='List plugins in the store')
parser_list.add_argument('queryparameters', nargs='*')
parser_list.add_argument('-v', '--verbose',
                         help="increase output verbosity by also including the plugin's"
                              " CLI parameters",
                         action='store_true')

# create the parser for the "add" command
parser_add = subparsers.add_parser('add', help='Add a new plugin')
parser_add.add_argument('name', help="Plugin's name")
parser_add.add_argument('dockerimage', help="Plugin's docker image name")
parser_add.add_argument("descriptorfile", type=str,
                        help="A json descriptor file with the plugin representation")
parser_add.add_argument('publicrepo', help="Plugin's public repo url")

# create the parser for the "modify" command
parser_modify = subparsers.add_parser('modify', help='Modify an existing plugin')
parser_modify.add_argument('id', help="Plugin's id")
parser_modify.add_argument('dockerimage', help="Plugin's new docker image name")
parser_modify.add_argument('publicrepo', help="Plugin's new public repo url")

# create the parser for the "remove" command
parser_remove = subparsers.add_parser('remove', help='Remove an existing plugin')
parser_remove.add_argument('id', help="Plugin's id")

# Parse the arguments and perform the appropriate action with the store client
args = parser.parse_args()
store_client = client.StoreClient(args.storeurl, args.username, args.password)

if args.subparser_name == 'list':
    search_params = {}
    for param_str in args.queryparameters:
        param_tuple = param_str.partition('==')
        search_params[param_tuple[0]] = param_tuple[2]
    result = store_client.get_plugins(search_params)
    print('')
    i = 0
    for plg in result['data']:
        i += 1
        print('[%i] ' % i)
        for descriptor in plg:
            print('%s: %s' % (descriptor, plg[descriptor]))
        if args.verbose:
            parameters = []
            offset = 0
            limit = 30
            while True:
                result = store_client.get_plugin_parameters(plg['id'], {'limit': limit,
                                                                        'offset': offset})
                parameters.extend(result['data'])
                offset += limit
                if not result['hasNextPage']: break
            print('parameters: %s' % parameters)
        print('')

if args.subparser_name == 'add':
    with open(args.descriptorfile, 'rb') as df:
        store_client.add_plugin(args.name, args.dockerimage, df, args.publicrepo)

if args.subparser_name == 'modify':
    store_client.modify_plugin(args.id, args.dockerimage, args.publicrepo)

if args.subparser_name == 'remove':
    store_client.remove_plugin(args.id)
