# coding=utf-8
# --------------------------------------------------------------------------
# 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.
# --------------------------------------------------------------------------

from msrest.pipeline import ClientRawResponse

from .. import models


class MetricsOperations(object):
    """MetricsOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer

        self.config = config

    def get(
            self, app_id, metric_id, timespan=None, interval=None, aggregation=None, segment=None, top=None, orderby=None, filter=None, custom_headers=None, raw=False, **operation_config):
        """Retrieve metric data.

        Gets metric values for a single metric.

        :param app_id: ID of the application. This is Application ID from the
         API Access settings blade in the Azure portal.
        :type app_id: str
        :param metric_id: ID of the metric. This is either a standard AI
         metric, or an application-specific custom metric. Possible values
         include: 'requests/count', 'requests/duration', 'requests/failed',
         'users/count', 'users/authenticated', 'pageViews/count',
         'pageViews/duration', 'client/processingDuration',
         'client/receiveDuration', 'client/networkDuration',
         'client/sendDuration', 'client/totalDuration', 'dependencies/count',
         'dependencies/failed', 'dependencies/duration', 'exceptions/count',
         'exceptions/browser', 'exceptions/server', 'sessions/count',
         'performanceCounters/requestExecutionTime',
         'performanceCounters/requestsPerSecond',
         'performanceCounters/requestsInQueue',
         'performanceCounters/memoryAvailableBytes',
         'performanceCounters/exceptionsPerSecond',
         'performanceCounters/processCpuPercentage',
         'performanceCounters/processIOBytesPerSecond',
         'performanceCounters/processPrivateBytes',
         'performanceCounters/processorCpuPercentage',
         'availabilityResults/availabilityPercentage',
         'availabilityResults/duration', 'billing/telemetryCount',
         'customEvents/count'
        :type metric_id: str or ~azure.applicationinsights.models.MetricId
        :param timespan: The timespan over which to retrieve metric values.
         This is an ISO8601 time period value. If timespan is omitted, a
         default time range of `PT12H` ("last 12 hours") is used. The actual
         timespan that is queried may be adjusted by the server based. In all
         cases, the actual time span used for the query is included in the
         response.
        :type timespan: str
        :param interval: The time interval to use when retrieving metric
         values. This is an ISO8601 duration. If interval is omitted, the
         metric value is aggregated across the entire timespan. If interval is
         supplied, the server may adjust the interval to a more appropriate
         size based on the timespan used for the query. In all cases, the
         actual interval used for the query is included in the response.
        :type interval: timedelta
        :param aggregation: The aggregation to use when computing the metric
         values. To retrieve more than one aggregation at a time, separate them
         with a comma. If no aggregation is specified, then the default
         aggregation for the metric is used.
        :type aggregation: list[str or
         ~azure.applicationinsights.models.MetricsAggregation]
        :param segment: The name of the dimension to segment the metric values
         by. This dimension must be applicable to the metric you are
         retrieving. To segment by more than one dimension at a time, separate
         them with a comma (,). In this case, the metric data will be segmented
         in the order the dimensions are listed in the parameter.
        :type segment: list[str or
         ~azure.applicationinsights.models.MetricsSegment]
        :param top: The number of segments to return.  This value is only
         valid when segment is specified.
        :type top: int
        :param orderby: The aggregation function and direction to sort the
         segments by.  This value is only valid when segment is specified.
        :type orderby: str
        :param filter: An expression used to filter the results.  This value
         should be a valid OData filter expression where the keys of each
         clause should be applicable dimensions for the metric you are
         retrieving.
        :type filter: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: MetricsResult or ClientRawResponse if raw=true
        :rtype: ~azure.applicationinsights.models.MetricsResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.applicationinsights.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'appId': self._serialize.url("app_id", app_id, 'str'),
            'metricId': self._serialize.url("metric_id", metric_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if timespan is not None:
            query_parameters['timespan'] = self._serialize.query("timespan", timespan, 'str')
        if interval is not None:
            query_parameters['interval'] = self._serialize.query("interval", interval, 'duration')
        if aggregation is not None:
            query_parameters['aggregation'] = self._serialize.query("aggregation", aggregation, '[MetricsAggregation]', div=',', min_items=1)
        if segment is not None:
            query_parameters['segment'] = self._serialize.query("segment", segment, '[str]', div=',', min_items=1)
        if top is not None:
            query_parameters['top'] = self._serialize.query("top", top, 'int')
        if orderby is not None:
            query_parameters['orderby'] = self._serialize.query("orderby", orderby, 'str')
        if filter is not None:
            query_parameters['filter'] = self._serialize.query("filter", filter, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('MetricsResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get.metadata = {'url': '/apps/{appId}/metrics/{metricId}'}

    def get_multiple(
            self, app_id, body, custom_headers=None, raw=False, **operation_config):
        """Retrieve metric data.

        Gets metric values for multiple metrics.

        :param app_id: ID of the application. This is Application ID from the
         API Access settings blade in the Azure portal.
        :type app_id: str
        :param body: The batched metrics query.
        :type body:
         list[~azure.applicationinsights.models.MetricsPostBodySchema]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: list or ClientRawResponse if raw=true
        :rtype: list[~azure.applicationinsights.models.MetricsResultsItem] or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.applicationinsights.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_multiple.metadata['url']
        path_format_arguments = {
            'appId': self._serialize.url("app_id", app_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct body
        body_content = self._serialize.body(body, '[MetricsPostBodySchema]')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('[MetricsResultsItem]', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_multiple.metadata = {'url': '/apps/{appId}/metrics'}

    def get_metadata(
            self, app_id, custom_headers=None, raw=False, **operation_config):
        """Retrieve metric metatadata.

        Gets metadata describing the available metrics.

        :param app_id: ID of the application. This is Application ID from the
         API Access settings blade in the Azure portal.
        :type app_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: object or ClientRawResponse if raw=true
        :rtype: object or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.applicationinsights.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_metadata.metadata['url']
        path_format_arguments = {
            'appId': self._serialize.url("app_id", app_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('object', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_metadata.metadata = {'url': '/apps/{appId}/metrics/metadata'}
