# --------------------------------------------------------------------------------------------
# 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 aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


@register_command(
    "sql mi dtc wait",
)
class Wait(AAZWaitCommand):
    """Place the CLI in a waiting state until a condition is met.
    """

    _aaz_info = {
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.sql/managedinstances/{}/dtc/{}", "2022-05-01-preview"],
        ]
    }

    def _handler(self, command_args):
        super()._handler(command_args)
        self._execute_operations()
        return self._output()

    _args_schema = None

    @classmethod
    def _build_arguments_schema(cls, *args, **kwargs):
        if cls._args_schema is not None:
            return cls._args_schema
        cls._args_schema = super()._build_arguments_schema(*args, **kwargs)

        # define Arg Group ""

        _args_schema = cls._args_schema
        _args_schema.managed_instance_name = AAZStrArg(
            options=["--mi", "--managed-instance-name"],
            help="The name of the managed instance.",
            required=True,
            id_part="name",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            help="Name of the resource group",
            required=True,
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.ManagedInstanceDtcsGet(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    def _output(self, *args, **kwargs):
        result = self.deserialize_output(self.ctx.vars.instance, client_flatten=False)
        return result

    class ManagedInstanceDtcsGet(AAZHttpOperation):
        CLIENT_TYPE = "MgmtClient"

        def __call__(self, *args, **kwargs):
            request = self.make_request()
            session = self.client.send_request(request=request, stream=False, **kwargs)
            if session.http_response.status_code in [200]:
                return self.on_200(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/dtc/{dtcName}",
                **self.url_parameters
            )

        @property
        def method(self):
            return "GET"

        @property
        def error_format(self):
            return "ODataV4Format"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "dtcName", "current",
                    required=True,
                ),
                **self.serialize_url_param(
                    "managedInstanceName", self.ctx.args.managed_instance_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2022-05-01-preview",
                    required=True,
                ),
            }
            return parameters

        @property
        def header_parameters(self):
            parameters = {
                **self.serialize_header_param(
                    "Accept", "application/json",
                ),
            }
            return parameters

        def on_200(self, session):
            data = self.deserialize_http_content(session)

            # Due to a bug in the API, the dtcHostName is returned as the dtcHostNameDnsSuffix property. Also the dtcHostName doesn't exist as a property currently.
            # The new API versions (with a fix) should return dtcHostName property and the correct value for dtcHostNameDnsSuffix.
            # Currently, as a workaround we check if the dtcHostName property exist.
            # If it doesn't exist, we create an additional field "dtcHostName" and display the "dtcHostNameDnsSuffix"
            # from the API response as the host name. Also, the dtcHostNameDnsSuffix is corrected to display the proper value.
            if 'dtcHostName' not in data['properties']:
                data['properties']['dtcHostName'] = data['properties']['dtcHostNameDnsSuffix']

                # Also, we extract the DNS suffix and display it properly.
                data['properties']['dtcHostNameDnsSuffix'] = data['properties']['dtcHostNameDnsSuffix'].split('.', 1)[1]
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_200
            )

        _schema_on_200 = None

        @classmethod
        def _build_schema_on_200(cls):
            if cls._schema_on_200 is not None:
                return cls._schema_on_200

            cls._schema_on_200 = AAZObjectType()

            _schema_on_200 = cls._schema_on_200
            _schema_on_200.id = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200.properties = AAZObjectType(
                flags={"client_flatten": True},
            )
            _schema_on_200.type = AAZStrType(
                flags={"read_only": True},
            )

            properties = cls._schema_on_200.properties
            properties.dtc_enabled = AAZBoolType(
                serialized_name="dtcEnabled",
            )
            properties.dtc_host_name_dns_suffix = AAZStrType(
                serialized_name="dtcHostNameDnsSuffix",
                flags={"read_only": True},
            )
            properties.dtc_host_name = AAZStrType(
                serialized_name="dtcHostName",
                flags={"read_only": True},
            )
            properties.external_dns_suffix_search_list = AAZListType(
                serialized_name="externalDnsSuffixSearchList",
            )
            properties.provisioning_state = AAZStrType(
                serialized_name="provisioningState",
                flags={"read_only": True},
            )
            properties.security_settings = AAZObjectType(
                serialized_name="securitySettings",
            )

            external_dns_suffix_search_list = cls._schema_on_200.properties.external_dns_suffix_search_list
            external_dns_suffix_search_list.Element = AAZStrType()

            security_settings = cls._schema_on_200.properties.security_settings
            security_settings.sna_lu6point2_transactions_enabled = AAZBoolType(
                serialized_name="snaLu6point2TransactionsEnabled",
            )
            security_settings.transaction_manager_communication_settings = AAZObjectType(
                serialized_name="transactionManagerCommunicationSettings",
            )
            security_settings.xa_transactions_default_timeout = AAZIntType(
                serialized_name="xaTransactionsDefaultTimeout",
            )
            security_settings.xa_transactions_enabled = AAZBoolType(
                serialized_name="xaTransactionsEnabled",
            )
            security_settings.xa_transactions_maximum_timeout = AAZIntType(
                serialized_name="xaTransactionsMaximumTimeout",
            )

            transaction_manager_communication_settings = cls._schema_on_200.properties.security_settings.transaction_manager_communication_settings
            transaction_manager_communication_settings.allow_inbound_enabled = AAZBoolType(
                serialized_name="allowInboundEnabled",
            )
            transaction_manager_communication_settings.allow_outbound_enabled = AAZBoolType(
                serialized_name="allowOutboundEnabled",
            )
            transaction_manager_communication_settings.authentication = AAZStrType()

            return cls._schema_on_200


class _WaitHelper:
    """Helper class for Wait"""


__all__ = ["Wait"]
