# --------------------------------------------------------------------------
# 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=too-many-lines
# pylint: disable=import-outside-toplevel

from azure.cli.core.util import sdk_no_wait


def cloud_service_create(cmd,
                         client,
                         resource_group_name,
                         cloud_service_name,
                         location=None,
                         tags=None,
                         package_url=None,
                         configuration=None,
                         configuration_url=None,
                         start_cloud_service=None,
                         upgrade_mode=None,
                         extensions=None,
                         load_balancer_configurations=None,
                         id_=None,
                         secrets=None,
                         roles=None,
                         no_wait=False):
    parameters = {}
    parameters['location'] = location
    parameters['tags'] = tags
    parameters['properties'] = {}
    parameters['properties']['package_url'] = package_url
    parameters['properties']['configuration'] = configuration
    parameters['properties']['configuration_url'] = configuration_url
    parameters['properties']['start_cloud_service'] = start_cloud_service
    parameters['properties']['upgrade_mode'] = upgrade_mode
    if extensions:
        parameters['properties']['extension_profile'] = {}
        parameters['properties']['extension_profile']['extensions'] = extensions
    else:
        parameters['properties']['extension_profile'] = None
    parameters['properties']['network_profile'] = {}
    parameters['properties']['network_profile']['load_balancer_configurations'] = _parse_lbs(
        load_balancer_configurations, cmd, resource_group_name)
    if id_:
        parameters['properties']['network_profile']['swappable_cloud_service'] = {}
        parameters['properties']['network_profile']['swappable_cloud_service']['id'] = id_
    else:
        parameters['properties']['network_profile']['swappable_cloud_service'] = None
    parameters['properties']['os_profile'] = {}
    parameters['properties']['os_profile']['secrets'] = _parse_secrets(
        secrets, cmd, resource_group_name)
    parameters['properties']['role_profile'] = {}
    parameters['properties']['role_profile']['roles'] = _parse_roles(roles)
    return sdk_no_wait(no_wait,
                       client.begin_create_or_update,
                       resource_group_name=resource_group_name,
                       cloud_service_name=cloud_service_name,
                       parameters=parameters)


def _parse_roles(roles):
    """
    Example, ContosoFrontend:Standard_D1_v2:1:Standard
    :param roles:
    :return:
    """
    if not roles:
        return None
    roles_json = []
    for role in roles:
        terms = role.split(':')
        roles_json.append({
            'sku': {
                'name': terms[1],
                'capacity': terms[2],
                'tier': terms[3]
            },
            'name': terms[0]
        })
    return roles_json


def _parse_lbs(lbs, cmd, resource_group_name):
    from msrestazure.tools import resource_id, is_valid_resource_id
    from azure.cli.core.commands.client_factory import get_subscription_id

    if not lbs:
        return None
    lbs_json = []
    for lb in lbs:
        terms = lb.split(':')
        ip = terms[2]
        subnet = terms[3]
        private_ip = terms[4]
        if ip and not is_valid_resource_id(ip):
            ip = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name,
                namespace='Microsoft.Network', type='publicIPAddresses', name=ip)
        lbs_json.append({
            'properties': {
                'frontendIPConfigurations': [
                    {
                        'properties': {
                            'publicIPAddress': {'id': ip} if ip else None,
                            'subnet': {'id': subnet} if subnet else None,
                            'privateIPAddress': private_ip if private_ip else None
                        },
                        'name': terms[1]
                    }
                ]
            },
            'name': terms[0]
        })
    return lbs_json


def _parse_secrets(secrets, cmd, resource_group_name):
    from msrestazure.tools import resource_id, is_valid_resource_id
    from azure.cli.core.commands.client_factory import get_subscription_id

    if not secrets:
        return None
    secrets_json = []
    for secret in secrets:
        terms = secret.split(':')
        vault = terms[0]
        certs = terms[1:]
        if vault and not is_valid_resource_id(vault):
            vault = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name,
                namespace='Microsoft.KeyVault', type='vaults', name=vault)
        secrets_json.append({
            'sourceVault': {
                'id': vault
            },
            'vaultCertificates': [
                {'certificateUrl': cert} for cert in certs
            ]
        })
    return secrets_json
