# --------------------------------------------------------------------------------------------
# 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(
    "monitor diagnostic-settings update",
)
class Update(AAZCommand):
    """Update diagnostic settings for the specified resource.
    """

    _aaz_info = {
        "version": "2021-05-01-preview",
        "resources": [
            ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/diagnosticsettings/{}", "2021-05-01-preview"],
        ]
    }

    AZ_SUPPORT_GENERIC_UPDATE = True

    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.name = AAZStrArg(
            options=["-n", "--name"],
            help="The name of the diagnostic setting. Required.",
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.event_hub_rule = AAZStrArg(
            options=["--event-hub-rule"],
            arg_group="Properties",
            help="The resource Id for the event hub authorization rule.",
            nullable=True,
        )
        _args_schema.event_hub = AAZStrArg(
            options=["--event-hub"],
            arg_group="Properties",
            help="The name of the event hub. If none is specified, the default event hub will be selected.",
            nullable=True,
        )
        _args_schema.log_analytics_destination_type = AAZStrArg(
            options=["--log-ana-dtype", "--log-analytics-destination-type"],
            arg_group="Properties",
            help="A string indicating whether the export to Log Analytics should use the default destination type, i.e. AzureDiagnostics, or use a destination type constructed as follows: `<normalized service identity>_<normalized category name>`. Possible values are: Dedicated and null (null is default.)",
            nullable=True,
        )
        _args_schema.logs = AAZListArg(
            options=["--logs"],
            arg_group="Properties",
            help="The list of logs settings.",
            nullable=True,
        )
        _args_schema.marketplace_partner_id = AAZStrArg(
            options=["--marketplace-partner-id"],
            arg_group="Properties",
            help="The full ARM resource ID of the Marketplace resource to which you would like to send Diagnostic Logs.",
            nullable=True,
        )
        _args_schema.metrics = AAZListArg(
            options=["--metrics"],
            arg_group="Properties",
            help="The list of metric settings.",
            nullable=True,
        )
        _args_schema.service_bus_rule_id = AAZStrArg(
            options=["--service-bus-rule-id"],
            arg_group="Properties",
            help="The service bus rule Id of the diagnostic setting. This is here to maintain backwards compatibility.",
            nullable=True,
        )
        _args_schema.storage_account_id = AAZStrArg(
            options=["--storage-account-id"],
            arg_group="Properties",
            help="The resource ID of the storage account to which you would like to send Diagnostic Logs.",
            nullable=True,
        )
        _args_schema.workspace_id = AAZStrArg(
            options=["--workspace-id"],
            arg_group="Properties",
            help="The full ARM resource ID of the Log Analytics workspace to which you would like to send Diagnostic Logs. Example: /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2",
            nullable=True,
        )

        logs = cls._args_schema.logs
        logs.Element = AAZObjectArg(
            nullable=True,
        )

        _element = cls._args_schema.logs.Element
        _element.category = AAZStrArg(
            options=["category"],
            help="Name of a Diagnostic Log category for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET diagnostic settings operation.",
            nullable=True,
        )
        _element.category_group = AAZStrArg(
            options=["category-group"],
            help="Name of a Diagnostic Log category group for a resource type this setting is applied to. To obtain the list of Diagnostic Log categories for a resource, first perform a GET diagnostic settings operation.",
            nullable=True,
        )
        _element.enabled = AAZBoolArg(
            options=["enabled"],
            help="a value indicating whether this log is enabled.",
        )
        _element.retention_policy = AAZObjectArg(
            options=["retention-policy"],
            help="the retention policy for this log.",
            nullable=True,
        )
        cls._build_args_retention_policy_update(_element.retention_policy)

        metrics = cls._args_schema.metrics
        metrics.Element = AAZObjectArg(
            nullable=True,
        )

        _element = cls._args_schema.metrics.Element
        _element.category = AAZStrArg(
            options=["category"],
            help="Name of a Diagnostic Metric category for a resource type this setting is applied to. To obtain the list of Diagnostic metric categories for a resource, first perform a GET diagnostic settings operation.",
            nullable=True,
        )
        _element.enabled = AAZBoolArg(
            options=["enabled"],
            help="a value indicating whether this category is enabled.",
        )
        _element.retention_policy = AAZObjectArg(
            options=["retention-policy"],
            help="the retention policy for this category.",
            nullable=True,
        )
        cls._build_args_retention_policy_update(_element.retention_policy)
        _element.time_grain = AAZDurationArg(
            options=["time-grain"],
            help="the timegrain of the metric in ISO8601 format.",
            nullable=True,
        )

        # define Arg Group "Target Resource"

        _args_schema = cls._args_schema
        _args_schema.resource = AAZStrArg(
            options=["--resource"],
            arg_group="Target Resource",
            help="Name or ID of the target resource.",
            required=True,
        )
        return cls._args_schema

    _args_retention_policy_update = None

    @classmethod
    def _build_args_retention_policy_update(cls, _schema):
        if cls._args_retention_policy_update is not None:
            _schema.days = cls._args_retention_policy_update.days
            _schema.enabled = cls._args_retention_policy_update.enabled
            return

        cls._args_retention_policy_update = AAZObjectArg(
            nullable=True,
        )

        retention_policy_update = cls._args_retention_policy_update
        retention_policy_update.days = AAZIntArg(
            options=["days"],
            help="the number of days for the retention in days. A value of 0 will retain the events indefinitely.",
            fmt=AAZIntArgFormat(
                minimum=0,
            ),
        )
        retention_policy_update.enabled = AAZBoolArg(
            options=["enabled"],
            help="a value indicating whether the retention policy is enabled.",
        )

        _schema.days = cls._args_retention_policy_update.days
        _schema.enabled = cls._args_retention_policy_update.enabled

    def _execute_operations(self):
        self.pre_operations()
        self.DiagnosticSettingsGet(ctx=self.ctx)()
        self.pre_instance_update(self.ctx.vars.instance)
        self.InstanceUpdateByJson(ctx=self.ctx)()
        self.InstanceUpdateByGeneric(ctx=self.ctx)()
        self.post_instance_update(self.ctx.vars.instance)
        self.DiagnosticSettingsCreateOrUpdate(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    @register_callback
    def pre_instance_update(self, instance):
        pass

    @register_callback
    def post_instance_update(self, instance):
        pass

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

    class DiagnosticSettingsGet(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(
                "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}",
                **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(
                    "name", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceUri", self.ctx.args.resource,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2021-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)
            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()
            _UpdateHelper._build_schema_diagnostic_settings_resource_read(cls._schema_on_200)

            return cls._schema_on_200

    class DiagnosticSettingsCreateOrUpdate(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(
                "/{resourceUri}/providers/Microsoft.Insights/diagnosticSettings/{name}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "name", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceUri", self.ctx.args.resource,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

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

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

        @property
        def content(self):
            _content_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=self.ctx.vars.instance,
            )

            return self.serialize_content(_content_value)

        def on_200(self, session):
            data = self.deserialize_http_content(session)
            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()
            _UpdateHelper._build_schema_diagnostic_settings_resource_read(cls._schema_on_200)

            return cls._schema_on_200

    class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance(self.ctx.vars.instance)

        def _update_instance(self, instance):
            _instance_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=instance,
                typ=AAZObjectType
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("eventHubAuthorizationRuleId", AAZStrType, ".event_hub_rule")
                properties.set_prop("eventHubName", AAZStrType, ".event_hub")
                properties.set_prop("logAnalyticsDestinationType", AAZStrType, ".log_analytics_destination_type")
                properties.set_prop("logs", AAZListType, ".logs")
                properties.set_prop("marketplacePartnerId", AAZStrType, ".marketplace_partner_id")
                properties.set_prop("metrics", AAZListType, ".metrics")
                properties.set_prop("serviceBusRuleId", AAZStrType, ".service_bus_rule_id")
                properties.set_prop("storageAccountId", AAZStrType, ".storage_account_id")
                properties.set_prop("workspaceId", AAZStrType, ".workspace_id")

            logs = _builder.get(".properties.logs")
            if logs is not None:
                logs.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.logs[]")
            if _elements is not None:
                _elements.set_prop("category", AAZStrType, ".category")
                _elements.set_prop("categoryGroup", AAZStrType, ".category_group")
                _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}})
                _UpdateHelper._build_schema_retention_policy_update(_elements.set_prop("retentionPolicy", AAZObjectType, ".retention_policy"))

            metrics = _builder.get(".properties.metrics")
            if metrics is not None:
                metrics.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.metrics[]")
            if _elements is not None:
                _elements.set_prop("category", AAZStrType, ".category")
                _elements.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}})
                _UpdateHelper._build_schema_retention_policy_update(_elements.set_prop("retentionPolicy", AAZObjectType, ".retention_policy"))
                _elements.set_prop("timeGrain", AAZStrType, ".time_grain")

            return _instance_value

    class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance_by_generic(
                self.ctx.vars.instance,
                self.ctx.generic_update_args
            )


class _UpdateHelper:
    """Helper class for Update"""

    @classmethod
    def _build_schema_retention_policy_update(cls, _builder):
        if _builder is None:
            return
        _builder.set_prop("days", AAZIntType, ".days", typ_kwargs={"flags": {"required": True}})
        _builder.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}})

    _schema_diagnostic_settings_resource_read = None

    @classmethod
    def _build_schema_diagnostic_settings_resource_read(cls, _schema):
        if cls._schema_diagnostic_settings_resource_read is not None:
            _schema.id = cls._schema_diagnostic_settings_resource_read.id
            _schema.name = cls._schema_diagnostic_settings_resource_read.name
            _schema.properties = cls._schema_diagnostic_settings_resource_read.properties
            _schema.system_data = cls._schema_diagnostic_settings_resource_read.system_data
            _schema.type = cls._schema_diagnostic_settings_resource_read.type
            return

        cls._schema_diagnostic_settings_resource_read = _schema_diagnostic_settings_resource_read = AAZObjectType()

        diagnostic_settings_resource_read = _schema_diagnostic_settings_resource_read
        diagnostic_settings_resource_read.id = AAZStrType(
            flags={"read_only": True},
        )
        diagnostic_settings_resource_read.name = AAZStrType(
            flags={"read_only": True},
        )
        diagnostic_settings_resource_read.properties = AAZObjectType(
            flags={"client_flatten": True},
        )
        diagnostic_settings_resource_read.system_data = AAZObjectType(
            serialized_name="systemData",
            flags={"read_only": True},
        )
        diagnostic_settings_resource_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_diagnostic_settings_resource_read.properties
        properties.event_hub_authorization_rule_id = AAZStrType(
            serialized_name="eventHubAuthorizationRuleId",
        )
        properties.event_hub_name = AAZStrType(
            serialized_name="eventHubName",
        )
        properties.log_analytics_destination_type = AAZStrType(
            serialized_name="logAnalyticsDestinationType",
        )
        properties.logs = AAZListType()
        properties.marketplace_partner_id = AAZStrType(
            serialized_name="marketplacePartnerId",
        )
        properties.metrics = AAZListType()
        properties.service_bus_rule_id = AAZStrType(
            serialized_name="serviceBusRuleId",
        )
        properties.storage_account_id = AAZStrType(
            serialized_name="storageAccountId",
        )
        properties.workspace_id = AAZStrType(
            serialized_name="workspaceId",
        )

        logs = _schema_diagnostic_settings_resource_read.properties.logs
        logs.Element = AAZObjectType()

        _element = _schema_diagnostic_settings_resource_read.properties.logs.Element
        _element.category = AAZStrType()
        _element.category_group = AAZStrType(
            serialized_name="categoryGroup",
        )
        _element.enabled = AAZBoolType(
            flags={"required": True},
        )
        _element.retention_policy = AAZObjectType(
            serialized_name="retentionPolicy",
        )
        cls._build_schema_retention_policy_read(_element.retention_policy)

        metrics = _schema_diagnostic_settings_resource_read.properties.metrics
        metrics.Element = AAZObjectType()

        _element = _schema_diagnostic_settings_resource_read.properties.metrics.Element
        _element.category = AAZStrType()
        _element.enabled = AAZBoolType(
            flags={"required": True},
        )
        _element.retention_policy = AAZObjectType(
            serialized_name="retentionPolicy",
        )
        cls._build_schema_retention_policy_read(_element.retention_policy)
        _element.time_grain = AAZStrType(
            serialized_name="timeGrain",
        )

        system_data = _schema_diagnostic_settings_resource_read.system_data
        system_data.created_at = AAZStrType(
            serialized_name="createdAt",
        )
        system_data.created_by = AAZStrType(
            serialized_name="createdBy",
        )
        system_data.created_by_type = AAZStrType(
            serialized_name="createdByType",
        )
        system_data.last_modified_at = AAZStrType(
            serialized_name="lastModifiedAt",
        )
        system_data.last_modified_by = AAZStrType(
            serialized_name="lastModifiedBy",
        )
        system_data.last_modified_by_type = AAZStrType(
            serialized_name="lastModifiedByType",
        )

        _schema.id = cls._schema_diagnostic_settings_resource_read.id
        _schema.name = cls._schema_diagnostic_settings_resource_read.name
        _schema.properties = cls._schema_diagnostic_settings_resource_read.properties
        _schema.system_data = cls._schema_diagnostic_settings_resource_read.system_data
        _schema.type = cls._schema_diagnostic_settings_resource_read.type

    _schema_retention_policy_read = None

    @classmethod
    def _build_schema_retention_policy_read(cls, _schema):
        if cls._schema_retention_policy_read is not None:
            _schema.days = cls._schema_retention_policy_read.days
            _schema.enabled = cls._schema_retention_policy_read.enabled
            return

        cls._schema_retention_policy_read = _schema_retention_policy_read = AAZObjectType()

        retention_policy_read = _schema_retention_policy_read
        retention_policy_read.days = AAZIntType(
            flags={"required": True},
        )
        retention_policy_read.enabled = AAZBoolType(
            flags={"required": True},
        )

        _schema.days = cls._schema_retention_policy_read.days
        _schema.enabled = cls._schema_retention_policy_read.enabled


__all__ = ["Update"]
