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

import uuid
from msrest.pipeline import ClientRawResponse

from .. import models


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

    You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    :ivar api_version: The API version to use for this operation. Constant value: "2019-09-01-preview".
    """

    models = models

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

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2019-09-01-preview"

        self.config = config

    def list(
            self, resource_group_name, query_pack_name, top=None, include_body=None, skip_token=None, custom_headers=None, raw=False, **operation_config):
        """Gets a list of Queries defined within a Log Analytics QueryPack.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param query_pack_name: The name of the Log Analytics QueryPack
         resource.
        :type query_pack_name: str
        :param top: Maximum items returned in page.
        :type top: int
        :param include_body: Flag indicating whether or not to return the body
         of each applicable query. If false, only return the query information.
        :type include_body: bool
        :param skip_token: Base64 encoded token used to fetch the next page of
         items. Default is null.
        :type skip_token: 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: An iterator like instance of LogAnalyticsQueryPackQuery
        :rtype:
         ~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQueryPaged[~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQuery]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.applicationinsights.v2019_09_01_preview.models.ErrorResponseException>`
        """
        def prepare_request(next_link=None):
            if not next_link:
                # Construct URL
                url = self.list.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
                    'queryPackName': self._serialize.url("query_pack_name", query_pack_name, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                if include_body is not None:
                    query_parameters['includeBody'] = self._serialize.query("include_body", include_body, 'bool')
                if skip_token is not None:
                    query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Accept'] = 'application/json'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters, header_parameters)
            return request

        def internal_paging(next_link=None):
            request = prepare_request(next_link)

            response = self._client.send(request, stream=False, **operation_config)

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

            return response

        # Deserialize response
        header_dict = None
        if raw:
            header_dict = {}
        deserialized = models.LogAnalyticsQueryPackQueryPaged(internal_paging, self._deserialize.dependencies, header_dict)

        return deserialized
    list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/queryPacks/{queryPackName}/queries'}

    def search(
            self, resource_group_name, query_pack_name, query_search_properties, top=None, include_body=None, skip_token=None, custom_headers=None, raw=False, **operation_config):
        """Search a list of Queries defined within a Log Analytics QueryPack
        according to given search properties.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param query_pack_name: The name of the Log Analytics QueryPack
         resource.
        :type query_pack_name: str
        :param query_search_properties: Properties by which to search queries
         in the given Log Analytics QueryPack.
        :type query_search_properties:
         ~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQuerySearchProperties
        :param top: Maximum items returned in page.
        :type top: int
        :param include_body: Flag indicating whether or not to return the body
         of each applicable query. If false, only return the query information.
        :type include_body: bool
        :param skip_token: Base64 encoded token used to fetch the next page of
         items. Default is null.
        :type skip_token: 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: An iterator like instance of LogAnalyticsQueryPackQuery
        :rtype:
         ~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQueryPaged[~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQuery]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.applicationinsights.v2019_09_01_preview.models.ErrorResponseException>`
        """
        def prepare_request(next_link=None):
            if not next_link:
                # Construct URL
                url = self.search.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
                    'queryPackName': self._serialize.url("query_pack_name", query_pack_name, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                if include_body is not None:
                    query_parameters['includeBody'] = self._serialize.query("include_body", include_body, 'bool')
                if skip_token is not None:
                    query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Accept'] = 'application/json'
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct body
            body_content = self._serialize.body(query_search_properties, 'LogAnalyticsQueryPackQuerySearchProperties')

            # Construct and send request
            request = self._client.post(url, query_parameters, header_parameters, body_content)
            return request

        def internal_paging(next_link=None):
            request = prepare_request(next_link)

            response = self._client.send(request, stream=False, **operation_config)

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

            return response

        # Deserialize response
        header_dict = None
        if raw:
            header_dict = {}
        deserialized = models.LogAnalyticsQueryPackQueryPaged(internal_paging, self._deserialize.dependencies, header_dict)

        return deserialized
    search.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/queryPacks/{queryPackName}/queries/search'}

    def get(
            self, resource_group_name, query_pack_name, query_id, custom_headers=None, raw=False, **operation_config):
        """Gets a specific Log Analytics Query defined within a Log Analytics
        QueryPack.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param query_pack_name: The name of the Log Analytics QueryPack
         resource.
        :type query_pack_name: str
        :param query_id: The id of a specific query defined in the Log
         Analytics QueryPack
        :type query_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: LogAnalyticsQueryPackQuery or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQuery
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.applicationinsights.v2019_09_01_preview.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
            'queryPackName': self._serialize.url("query_pack_name", query_pack_name, 'str'),
            'queryId': self._serialize.url("query_id", query_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # 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('LogAnalyticsQueryPackQuery', response)

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

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/queryPacks/{queryPackName}/queries/{queryId}'}

    def put(
            self, resource_group_name, query_pack_name, query_id, query_payload, custom_headers=None, raw=False, **operation_config):
        """Adds or Updates a specific Query within a Log Analytics QueryPack.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param query_pack_name: The name of the Log Analytics QueryPack
         resource.
        :type query_pack_name: str
        :param query_id: The id of a specific query defined in the Log
         Analytics QueryPack
        :type query_id: str
        :param query_payload: Properties that need to be specified to create a
         new query and add it to a Log Analytics QueryPack.
        :type query_payload:
         ~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQuery
        :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: LogAnalyticsQueryPackQuery or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.applicationinsights.v2019_09_01_preview.models.LogAnalyticsQueryPackQuery
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.applicationinsights.v2019_09_01_preview.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.put.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
            'queryPackName': self._serialize.url("query_pack_name", query_pack_name, 'str'),
            'queryId': self._serialize.url("query_id", query_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(query_payload, 'LogAnalyticsQueryPackQuery')

        # Construct and send request
        request = self._client.put(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('LogAnalyticsQueryPackQuery', response)

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

        return deserialized
    put.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/queryPacks/{queryPackName}/queries/{queryId}'}

    def delete(
            self, resource_group_name, query_pack_name, query_id, custom_headers=None, raw=False, **operation_config):
        """Deletes a specific Query defined within an Log Analytics QueryPack.

        :param resource_group_name: The name of the resource group. The name
         is case insensitive.
        :type resource_group_name: str
        :param query_pack_name: The name of the Log Analytics QueryPack
         resource.
        :type query_pack_name: str
        :param query_id: The id of a specific query defined in the Log
         Analytics QueryPack
        :type query_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: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.applicationinsights.v2019_09_01_preview.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.delete.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str', min_length=1),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
            'queryPackName': self._serialize.url("query_pack_name", query_pack_name, 'str'),
            'queryId': self._serialize.url("query_id", query_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str', min_length=1)

        # Construct headers
        header_parameters = {}
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

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

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

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
    delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/queryPacks/{queryPackName}/queries/{queryId}'}
