# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------


# pylint: disable=protected-access

# pylint: disable=no-self-use


import argparse
from collections import defaultdict
from knack.util import CLIError


class AddSubnets(argparse._AppendAction):
    def __call__(self, parser, namespace, values, option_string=None):
        action = self.get_action(values, option_string)
        for item in action:
            super(AddSubnets, self).__call__(parser, namespace, item, option_string)

    def get_action(self, values, option_string):
        ret = []
        for item in values:
            properties = defaultdict(list)
            try:
                for (k, v) in (x.split('=', 1) for x in item.split(',')):
                    properties[k].append(v)
                properties = dict(properties)
            except ValueError:
                raise CLIError('usage error: {} [KEY=VALUE ...]'.format(option_string))
            d = {}
            for k in properties:
                kl = k.lower()
                v = properties[k]

                if kl == 'id':
                    d['id'] = v[0]

                elif kl == 'name':
                    d['name'] = v[0]

                elif kl == 'alias':
                    sub_d = d
                    if 'company' not in sub_d:
                        sub_d['company'] = {}
                    sub_d = sub_d['company']

                    if 'info' not in sub_d:
                        sub_d['info'] = {}
                    sub_d = sub_d['info']

                    sub_d['alias'] = v[0]

                else:
                    raise CLIError(
                        'Unsupported Key {} is provided for parameter subnets. All possible keys are: id, name, alias'
                        .format(k)
                    )

            ret.append(d)
        return ret
