# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
#     Copyright (c) 2016 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import json

from cdpcli.argprocess import ParamError
from cdpcli.extensions.arguments import OverrideRequiredArgsArgument
from cdpcli.paramfile import get_paramfile
from cdpcli.paramfile import ParamFileVisitor


def add_cli_input_json(operation_model, argument_table):
    cli_input_json_argument = CliInputJSONArgument(operation_model)
    cli_input_json_argument.add_to_arg_table(argument_table)


class CliInputJSONArgument(OverrideRequiredArgsArgument):
    """This argument inputs a JSON string as the entire input for a command.

    Ideally, the value to this argument should be a filled out JSON file
    generated by ``--generate-cli-skeleton``. The items in the JSON string
    will not clobber other arguments entered into the command line.
    """
    ARG_DATA = {
        'name': 'cli-input-json',
        'help_text': 'Performs service operation based on the JSON string '
                     'provided. The JSON string follows the format provided '
                     'by ``--generate-cli-skeleton``. If other arguments are '
                     'provided on the command line, the CLI values will override '
                     'the JSON-provided values.'
    }

    def __init__(self, operation_model):
        super(CliInputJSONArgument, self).__init__()
        self._operation_model = operation_model

    def invoke(self,
               client_creator,
               operation_model,
               parameters,
               parsed_args,
               parsed_globals):
        return self.add_to_call_parameters(parameters, parsed_args)

    def add_to_call_parameters(self, call_parameters, parsed_args):

        # Check if ``--cli-input-json`` was specified in the command line.
        input_json = getattr(parsed_args, 'cli_input_json', None)
        if input_json is not None:
            # Retrieve the JSON from the file if needed.
            retrieved_json = get_paramfile(input_json)
            # Nothing was retrieved from the file. So assume the argument
            # is already a JSON string.
            if retrieved_json is None:
                retrieved_json = input_json
            try:
                # Try to load the JSON string into a python dictionary
                input_data = json.loads(retrieved_json)
            except ValueError as e:
                raise ParamError(
                    self.name, "Invalid JSON: %s\nJSON received: %s"
                               % (e, retrieved_json))
            # We run the ParamFileVisitor over the input data to resolve any
            # paramfile references in it.
            input_data = ParamFileVisitor().visit(
                input_data, self._operation_model.input_shape)
            # Add the members from the input JSON to the call parameters.
            self._update_call_parameters(call_parameters, input_data)
        return True

    def _update_call_parameters(self, call_parameters, input_data):
        for input_key in input_data.keys():
            # Only add the values to ``call_parameters`` if not already
            # present.
            if input_key not in call_parameters:
                call_parameters[input_key] = input_data[input_key]
