# --------------------------------------------------------------------------------------------
# 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 metrics list-sub",
)
class ListSub(AAZCommand):
    """Lists the metric data for a subscription. Parameters can be specified on the body.
    """

    _aaz_info = {
        "version": "2023-10-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/providers/microsoft.insights/metrics", "2023-10-01"],
        ]
    }

    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.region = AAZStrArg(
            options=["--region"],
            help="The region where the metrics you want reside.",
            required=True,
        )

        # define Arg Group "Body"

        _args_schema = cls._args_schema
        _args_schema.aggregation = AAZStrArg(
            options=["--aggregation"],
            arg_group="Body",
            help="The list of aggregation types (comma separated) to retrieve.",
        )
        _args_schema.auto_adjust_timegrain = AAZBoolArg(
            options=["--auto-adjust-timegrain"],
            arg_group="Body",
            help="When set to true, if the timespan passed in is not supported by this metric, the API will return the result using the closest supported timespan. When set to false, an error is returned for invalid timespan parameters. Defaults to false.",
        )
        _args_schema.filter = AAZStrArg(
            options=["--filter"],
            arg_group="Body",
            help="The **$filter** is used to reduce the set of metric data returned.<br>Example:<br>Metric contains metadata A, B and C.<br>- Return all time series of C where A = a1 and B = b1 or b2<br>**$filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**<br>- Invalid variant:<br>**$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**<br>This is invalid because the logical or operator cannot separate two different metadata names.<br>- Return all time series where A = a1, B = b1 and C = c1:<br>**$filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**<br>- Return all time series where A = a1<br>**$filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.",
        )
        _args_schema.interval = AAZStrArg(
            options=["--interval"],
            arg_group="Body",
            help="The interval (i.e. timegrain) of the query in ISO 8601 duration format. Defaults to PT1M. Special case for 'FULL' value that returns single datapoint for entire time span requested. *Examples: PT15M, PT1H, P1D, FULL*",
        )
        _args_schema.metricnames = AAZStrArg(
            options=["--metricnames"],
            arg_group="Body",
            help="The names of the metrics (comma separated) to retrieve.",
        )
        _args_schema.metricnamespace = AAZStrArg(
            options=["--metricnamespace"],
            arg_group="Body",
            help="Metric namespace where the metrics you want reside.",
        )
        _args_schema.order_by = AAZStrArg(
            options=["--order-by"],
            arg_group="Body",
            help="The aggregation to use for sorting results and the direction of the sort. Only one order can be specified. Examples: sum asc.",
        )
        _args_schema.result_type = AAZStrArg(
            options=["--result-type"],
            arg_group="Body",
            help="Reduces the set of data collected. The syntax allowed depends on the operation. See the operation's description for details.",
            enum={"Data": "Data", "Metadata": "Metadata"},
        )
        _args_schema.roll_up_by = AAZStrArg(
            options=["--roll-up-by"],
            arg_group="Body",
            help="Dimension name(s) to rollup results by. For example if you only want to see metric values with a filter like 'City eq Seattle or City eq Tacoma' but don't want to see separate values for each city, you can specify 'RollUpBy=City' to see the results for Seattle and Tacoma rolled up into one timeseries.",
        )
        _args_schema.timespan = AAZStrArg(
            options=["--timespan"],
            arg_group="Body",
            help="The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.",
        )
        _args_schema.top = AAZIntArg(
            options=["--top"],
            arg_group="Body",
            help="The maximum number of records to retrieve. Valid only if $filter is specified. Defaults to 10.",
        )
        _args_schema.validate_dimensions = AAZBoolArg(
            options=["--validate-dimensions"],
            arg_group="Body",
            help="When set to false, invalid filter parameter values will be ignored. When set to true, an error is returned for invalid filter parameters. Defaults to true.",
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.MetricsListAtSubscriptionScopePost(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=True)
        return result

    class MetricsListAtSubscriptionScopePost(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}/providers/Microsoft.Insights/metrics",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "region", self.ctx.args.region,
                    required=True,
                ),
                **self.serialize_query_param(
                    "api-version", "2023-10-01",
                    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,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"client_flatten": True}}
            )
            _builder.set_prop("aggregation", AAZStrType, ".aggregation")
            _builder.set_prop("autoAdjustTimegrain", AAZBoolType, ".auto_adjust_timegrain")
            _builder.set_prop("filter", AAZStrType, ".filter")
            _builder.set_prop("interval", AAZStrType, ".interval")
            _builder.set_prop("metricNames", AAZStrType, ".metricnames")
            _builder.set_prop("metricNamespace", AAZStrType, ".metricnamespace")
            _builder.set_prop("orderBy", AAZStrType, ".order_by")
            _builder.set_prop("resultType", AAZStrType, ".result_type")
            _builder.set_prop("rollUpBy", AAZStrType, ".roll_up_by")
            _builder.set_prop("timespan", AAZStrType, ".timespan")
            _builder.set_prop("top", AAZIntType, ".top")
            _builder.set_prop("validateDimensions", AAZBoolType, ".validate_dimensions")

            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()

            _schema_on_200 = cls._schema_on_200
            _schema_on_200.cost = AAZIntType()
            _schema_on_200.interval = AAZStrType()
            _schema_on_200.namespace = AAZStrType()
            _schema_on_200.resourceregion = AAZStrType()
            _schema_on_200.timespan = AAZStrType(
                flags={"required": True},
            )
            _schema_on_200.value = AAZListType(
                flags={"required": True},
            )

            value = cls._schema_on_200.value
            value.Element = AAZObjectType()

            _element = cls._schema_on_200.value.Element
            _element.display_description = AAZStrType(
                serialized_name="displayDescription",
            )
            _element.error_code = AAZStrType(
                serialized_name="errorCode",
            )
            _element.error_message = AAZStrType(
                serialized_name="errorMessage",
            )
            _element.id = AAZStrType(
                flags={"required": True},
            )
            _element.name = AAZObjectType(
                flags={"required": True},
            )
            _ListSubHelper._build_schema_localizable_string_read(_element.name)
            _element.timeseries = AAZListType(
                flags={"required": True},
            )
            _element.type = AAZStrType(
                flags={"required": True},
            )
            _element.unit = AAZStrType(
                flags={"required": True},
            )

            timeseries = cls._schema_on_200.value.Element.timeseries
            timeseries.Element = AAZObjectType()

            _element = cls._schema_on_200.value.Element.timeseries.Element
            _element.data = AAZListType()
            _element.metadatavalues = AAZListType()

            data = cls._schema_on_200.value.Element.timeseries.Element.data
            data.Element = AAZObjectType()

            _element = cls._schema_on_200.value.Element.timeseries.Element.data.Element
            _element.average = AAZFloatType()
            _element.count = AAZFloatType()
            _element.maximum = AAZFloatType()
            _element.minimum = AAZFloatType()
            _element.time_stamp = AAZStrType(
                serialized_name="timeStamp",
                flags={"required": True},
            )
            _element.total = AAZFloatType()

            metadatavalues = cls._schema_on_200.value.Element.timeseries.Element.metadatavalues
            metadatavalues.Element = AAZObjectType()

            _element = cls._schema_on_200.value.Element.timeseries.Element.metadatavalues.Element
            _element.name = AAZObjectType()
            _ListSubHelper._build_schema_localizable_string_read(_element.name)
            _element.value = AAZStrType()

            return cls._schema_on_200


class _ListSubHelper:
    """Helper class for ListSub"""

    _schema_localizable_string_read = None

    @classmethod
    def _build_schema_localizable_string_read(cls, _schema):
        if cls._schema_localizable_string_read is not None:
            _schema.localized_value = cls._schema_localizable_string_read.localized_value
            _schema.value = cls._schema_localizable_string_read.value
            return

        cls._schema_localizable_string_read = _schema_localizable_string_read = AAZObjectType()

        localizable_string_read = _schema_localizable_string_read
        localizable_string_read.localized_value = AAZStrType(
            serialized_name="localizedValue",
        )
        localizable_string_read.value = AAZStrType(
            flags={"required": True},
        )

        _schema.localized_value = cls._schema_localizable_string_read.localized_value
        _schema.value = cls._schema_localizable_string_read.value


__all__ = ["ListSub"]
