# coding: utf-8

from __future__ import absolute_import
from __future__ import print_function

import inspect
import pprint
import requests
import sys

from . import config


def command(parser, args):
    """ Interact with Ambari blueprints. """
    subparsers = parser.add_subparsers(dest='subcommand')
    subcommands = {
        'list': _list,
        }
    for name, fn in subcommands.items():
        subparsers.add_parser(name, help=inspect.getdoc(fn))
    subargs, extra = parser.parse_known_args(args)
    subcommands[subargs.subcommand](
        subparsers.choices[subargs.subcommand],
        extra)


def _list(parser, args):
    """ List all blueprints stored on the Ambari server. """
    parser.add_argument(
        '--fields',
        help="Print blueprint details.")
    subargs = parser.parses_args(args)
    response = requests.get(
        config.href('/api/v1/blueprints'),
        params={'fields': subargs.fields},
        **config.requests_opts())
    if config.args.raw:
        pprint.pprint(response.json())
        sys.exit(0)
    response.raise_for_status()
    for item in response.json()['items']:
        print('{name}'.format(name=item['Blueprints']['blueprint_name']))
        del item['Blueprints']['blueprint_name']
        for key, value in item.items():
            if key != 'href':
                config.print_field(k=key, v=value, indent=4)

@@ -95,23 +95,51 @@
 %0Aimport 
-inspect
+argparse%0Aimport inspect%0Aimport json
 %0Aimport 
@@ -346,16 +346,37 @@
 nds = %7B%0A
+        'add': _add,%0A
         
@@ -638,16 +638,16 @@
 mmand%5D,%0A
-
         
@@ -655,16 +655,1084 @@
 xtra)%0A%0A%0A
+def _add(parser, args):%0A    %22%22%22 Add a blueprint to the Ambari server. %22%22%22%0A    parser.add_argument(%0A        '--validate-topology',%0A        help=%22Specify whether to validate a blueprint on upload.%22)%0A    parser.add_argument(%0A        'blueprint',%0A        nargs='*',%0A        help=%22Specify a blueprint to add to the Ambari server.%22)%0A    subargs = parser.parse_args(args)%0A    blueprints = %5B%5D if len(subargs.blueprint) %3E 0 else %5Bsys.stdin.read()%5D%0A    for blueprint_file in subargs.blueprint:%0A        with open(blueprint_file, 'r') as f:%0A            blueprints.append(f.read())%0A    for blueprint in blueprints:%0A        blueprint = json.loads(blueprint)%0A        response = requests.post(%0A            config.href(%0A                '/api/v1/blueprints/%7Bname%7D'.format(%0A                    name=blueprint%5B'Blueprints'%5D%5B'blueprint_name'%5D)),%0A            data=json.dumps(blueprint),  # %60json=blueprint%60 would be better, but it doesn't work!%0A            params=%7B'validate_topology': subargs.validate_topology%7D,%0A            **config.requests_opts())%0A        response.raise_for_status()%0A%0A%0A
 def _lis

Implement blueprint add.