# --------------------------------------------------------------------------------------------
# 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 *


class List(AAZCommand):
    """List the metric values for a resource.
    """

    _aaz_info = {
        "version": "2018-01-01",
        "resources": [
            ["mgmt-plane", "/{resourceuri}/providers/microsoft.insights/metrics", "2018-01-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.resource_uri = AAZStrArg(
            options=["--resource-uri"],
            help="The identifier of the resource.",
            required=True,
        )
        _args_schema.aggregation = AAZStrArg(
            options=["--aggregation"],
            help="The list of aggregation types (comma separated) to retrieve.",
        )
        _args_schema.filter = AAZStrArg(
            options=["--filter"],
            help="The **$filter** is used to reduce the set of metric data returned. Example: Metric contains metadata A, B and C. - Return all time series of C where A = a1 and B = b1 or b2 **$filter=A eq 'a1' and B eq 'b1' or B eq 'b2' and C eq '*'** - Invalid variant: **$filter=A eq 'a1' and B eq 'b1' and C eq '*' or B = 'b2'** This is invalid because the logical or operator cannot separate two different metadata names. - Return all time series where A = a1, B = b1 and C = c1: **$filter=A eq 'a1' and B eq 'b1' and C eq 'c1'** - Return all time series where A = a1 **$filter=A eq 'a1' and B eq '*' and C eq '*'**. Special case: When dimension name or dimension value uses round brackets. Eg: When dimension name is **dim (test) 1** Instead of using $filter= \"dim (test) 1 eq '*' \" use **$filter= \"dim %2528test%2529 1 eq '*' \"** When dimension name is **dim (test) 3** and dimension value is **dim3 (test) val** Instead of using $filter= \"dim (test) 3 eq 'dim3 (test) val' \" use **$filter= \"dim %2528test%2529 3 eq 'dim3 %2528test%2529 val' \"**",
        )
        _args_schema.interval = AAZDurationArg(
            options=["--interval"],
            help="The interval (i.e. timegrain) of the query.",
        )
        _args_schema.metricnames = AAZStrArg(
            options=["--metricnames"],
            help="The names of the metrics (comma separated) to retrieve. Special case: If a metricname itself has a comma in it then use %2 to indicate it. Eg: 'Metric,Name1' should be **'Metric%2Name1'**",
        )
        _args_schema.metricnamespace = AAZStrArg(
            options=["--metricnamespace"],
            help="Metric namespace to query metric definitions for.",
        )
        _args_schema.orderby = AAZStrArg(
            options=["--orderby"],
            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"],
            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.timespan = AAZStrArg(
            options=["--timespan"],
            help="The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.",
        )
        _args_schema.top = AAZIntArg(
            options=["--top"],
            help="The maximum number of records to retrieve. Valid only if $filter is specified. Defaults to 10.",
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.MetricsList(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 MetricsList(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/metrics",
                **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(
                    "resourceUri", self.ctx.args.resource_uri,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "$filter", self.ctx.args.filter,
                ),
                **self.serialize_query_param(
                    "aggregation", self.ctx.args.aggregation,
                ),
                **self.serialize_query_param(
                    "interval", self.ctx.args.interval,
                ),
                **self.serialize_query_param(
                    "metricnames", self.ctx.args.metricnames,
                ),
                **self.serialize_query_param(
                    "metricnamespace", self.ctx.args.metricnamespace,
                ),
                **self.serialize_query_param(
                    "orderby", self.ctx.args.orderby,
                ),
                **self.serialize_query_param(
                    "resultType", self.ctx.args.result_type,
                ),
                **self.serialize_query_param(
                    "timespan", self.ctx.args.timespan,
                ),
                **self.serialize_query_param(
                    "top", self.ctx.args.top,
                ),
                **self.serialize_query_param(
                    "api-version", "2018-01-01",
                    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()

            _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},
            )
            _ListHelper._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()
            _ListHelper._build_schema_localizable_string_read(_element.name)
            _element.value = AAZStrType()

            return cls._schema_on_200


class _ListHelper:
    """Helper class for List"""

    _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__ = ["List"]
