# 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 typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union
import warnings

from azure.core.exceptions import map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse

from .. import models

T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

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

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

    :ivar models: Alias to model classes used in this operation group.
    :type models: ~storage_import_export.models
    :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 list_by_subscription(
        self,
        top=None,  # type: Optional[int]
        filter=None,  # type: Optional[str]
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.ListJobsResponse"
        """Returns all active and completed jobs in a subscription.

        :param top: An integer value that specifies how many jobs at most should be returned. The value
         cannot exceed 100.
        :type top: int
        :param filter: Can be used to restrict the results to certain conditions.
        :type filter: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ListJobsResponse or the result of cls(response)
        :rtype: ~storage_import_export.models.ListJobsResponse
        :raises: ~storage_import_export.models.ErrorResponseException:
        """
        cls = kwargs.pop('cls', None )  # type: ClsType["models.ListJobsResponse"]
        error_map = kwargs.pop('error_map', {})
        api_version = "2016-11-01"

        def prepare_request(next_link=None):
            if not next_link:
                # Construct URL
                url = self.list_by_subscription.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            if self._config.acceptlanguage is not None:
                header_parameters['Accept-Language'] = self._serialize.header("self._config.acceptlanguage", self._config.acceptlanguage, 'str')
            header_parameters['Accept'] = 'application/json'

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

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ListJobsResponse', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link, iter(list_of_elem)

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

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

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

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ImportExport/jobs'}

    def list_by_resource_group(
        self,
        resource_group_name,  # type: str
        top=None,  # type: Optional[int]
        filter=None,  # type: Optional[str]
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.ListJobsResponse"
        """Returns all active and completed jobs in a resource group.

        :param resource_group_name: The resource group name uniquely identifies the resource group
         within the user subscription.
        :type resource_group_name: str
        :param top: An integer value that specifies how many jobs at most should be returned. The value
         cannot exceed 100.
        :type top: int
        :param filter: Can be used to restrict the results to certain conditions.
        :type filter: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ListJobsResponse or the result of cls(response)
        :rtype: ~storage_import_export.models.ListJobsResponse
        :raises: ~storage_import_export.models.ErrorResponseException:
        """
        cls = kwargs.pop('cls', None )  # type: ClsType["models.ListJobsResponse"]
        error_map = kwargs.pop('error_map', {})
        api_version = "2016-11-01"

        def prepare_request(next_link=None):
            if not next_link:
                # Construct URL
                url = self.list_by_resource_group.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            if self._config.acceptlanguage is not None:
                header_parameters['Accept-Language'] = self._serialize.header("self._config.acceptlanguage", self._config.acceptlanguage, 'str')
            header_parameters['Accept'] = 'application/json'

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

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ListJobsResponse', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link, iter(list_of_elem)

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

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

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

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ImportExport/jobs'}

    def get(
        self,
        job_name,  # type: str
        resource_group_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.JobResponse"
        """Gets information about an existing job.

        :param job_name: The name of the import/export job.
        :type job_name: str
        :param resource_group_name: The resource group name uniquely identifies the resource group
         within the user subscription.
        :type resource_group_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: JobResponse or the result of cls(response)
        :rtype: ~storage_import_export.models.JobResponse
        :raises: ~storage_import_export.models.ErrorResponseException:
        """
        cls = kwargs.pop('cls', None )  # type: ClsType["models.JobResponse"]
        error_map = kwargs.pop('error_map', {})
        api_version = "2016-11-01"

        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'jobName': self._serialize.url("job_name", job_name, 'str'),
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

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

        # Construct headers
        header_parameters = {}
        if self._config.acceptlanguage is not None:
            header_parameters['Accept-Language'] = self._serialize.header("self._config.acceptlanguage", self._config.acceptlanguage, 'str')
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

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

        deserialized = self._deserialize('JobResponse', pipeline_response)

        if cls:
          return cls(pipeline_response, deserialized, {})

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ImportExport/jobs/{jobName}'}

    def update(
        self,
        job_name,  # type: str
        resource_group_name,  # type: str
        tags=None,  # type: Optional["models.UpdateJobParametersTags"]
        cancel_requested=None,  # type: Optional[bool]
        state=None,  # type: Optional[str]
        return_address=None,  # type: Optional["models.ReturnAddress"]
        return_shipping=None,  # type: Optional["models.ReturnShipping"]
        delivery_package=None,  # type: Optional["models.PackageInfomation"]
        log_level=None,  # type: Optional[str]
        backup_drive_manifest=None,  # type: Optional[bool]
        drive_list=None,  # type: Optional[List["DriveStatus"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.JobResponse"
        """Updates specific properties of a job. You can call this operation to notify the Import/Export service that the hard drives comprising the import or export job have been shipped to the Microsoft data center. It can also be used to cancel an existing job.

        :param job_name: The name of the import/export job.
        :type job_name: str
        :param resource_group_name: The resource group name uniquely identifies the resource group
         within the user subscription.
        :type resource_group_name: str
        :param tags: Specifies the tags that will be assigned to the job.
        :type tags: ~storage_import_export.models.UpdateJobParametersTags
        :param cancel_requested: If specified, the value must be true. The service will attempt to
         cancel the job.
        :type cancel_requested: bool
        :param state: If specified, the value must be Shipping, which tells the Import/Export service
         that the package for the job has been shipped. The ReturnAddress and DeliveryPackage properties
         must have been set either in this request or in a previous request, otherwise the request will
         fail.
        :type state: str
        :param return_address: Specifies the return address information for the job.
        :type return_address: ~storage_import_export.models.ReturnAddress
        :param return_shipping: Specifies the return carrier and customer's account with the carrier.
        :type return_shipping: ~storage_import_export.models.ReturnShipping
        :param delivery_package: Contains information about the package being shipped by the customer
         to the Microsoft data center.
        :type delivery_package: ~storage_import_export.models.PackageInfomation
        :param log_level: Indicates whether error logging or verbose logging is enabled.
        :type log_level: str
        :param backup_drive_manifest: Indicates whether the manifest files on the drives should be
         copied to block blobs.
        :type backup_drive_manifest: bool
        :param drive_list: List of drives that comprise the job.
        :type drive_list: list[~storage_import_export.models.DriveStatus]
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: JobResponse or the result of cls(response)
        :rtype: ~storage_import_export.models.JobResponse
        :raises: ~storage_import_export.models.ErrorResponseException:
        """
        cls = kwargs.pop('cls', None )  # type: ClsType["models.JobResponse"]
        error_map = kwargs.pop('error_map', {})

        body = models.UpdateJobParameters(tags=tags, cancel_requested=cancel_requested, state=state, return_address=return_address, return_shipping=return_shipping, delivery_package=delivery_package, log_level=log_level, backup_drive_manifest=backup_drive_manifest, drive_list=drive_list)
        api_version = "2016-11-01"

        # Construct URL
        url = self.update.metadata['url']
        path_format_arguments = {
            'jobName': self._serialize.url("job_name", job_name, 'str'),
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

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

        # Construct headers
        header_parameters = {}
        if self._config.acceptlanguage is not None:
            header_parameters['Accept-Language'] = self._serialize.header("self._config.acceptlanguage", self._config.acceptlanguage, 'str')
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json'

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

        # Construct and send request
        request = self._client.patch(url, query_parameters, header_parameters, body_content)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

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

        deserialized = self._deserialize('JobResponse', pipeline_response)

        if cls:
          return cls(pipeline_response, deserialized, {})

        return deserialized
    update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ImportExport/jobs/{jobName}'}

    def create(
        self,
        job_name,  # type: str
        resource_group_name,  # type: str
        client_tenant_id=None,  # type: Optional[str]
        location=None,  # type: Optional[str]
        tags=None,  # type: Optional["models.PutJobParametersTags"]
        storage_account_id=None,  # type: Optional[str]
        job_type=None,  # type: Optional[str]
        return_address=None,  # type: Optional["models.ReturnAddress"]
        return_shipping=None,  # type: Optional["models.ReturnShipping"]
        shipping_information=None,  # type: Optional["models.ShippingInformation"]
        delivery_package=None,  # type: Optional["models.PackageInfomation"]
        return_package=None,  # type: Optional["models.PackageInfomation"]
        diagnostics_path=None,  # type: Optional[str]
        log_level=None,  # type: Optional[str]
        backup_drive_manifest=None,  # type: Optional[bool]
        state=None,  # type: Optional[str]
        cancel_requested=None,  # type: Optional[bool]
        percent_complete=None,  # type: Optional[int]
        incomplete_blob_list_uri=None,  # type: Optional[str]
        drive_list=None,  # type: Optional[List["DriveStatus"]]
        export=None,  # type: Optional["models.Export"]
        provisioning_state=None,  # type: Optional[str]
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.JobResponse"
        """Creates a new job or updates an existing job in the specified subscription.

        :param job_name: The name of the import/export job.
        :type job_name: str
        :param resource_group_name: The resource group name uniquely identifies the resource group
         within the user subscription.
        :type resource_group_name: str
        :param client_tenant_id: The tenant ID of the client making the request.
        :type client_tenant_id: str
        :param location: Specifies the supported Azure location where the job should be created.
        :type location: str
        :param tags: Specifies the tags that will be assigned to the job.
        :type tags: ~storage_import_export.models.PutJobParametersTags
        :param storage_account_id: The resource identifier of the storage account where data will be
         imported to or exported from.
        :type storage_account_id: str
        :param job_type: The type of job.
        :type job_type: str
        :param return_address: Specifies the return address information for the job.
        :type return_address: ~storage_import_export.models.ReturnAddress
        :param return_shipping: Specifies the return carrier and customer's account with the carrier.
        :type return_shipping: ~storage_import_export.models.ReturnShipping
        :param shipping_information: Contains information about the Microsoft datacenter to which the
         drives should be shipped.
        :type shipping_information: ~storage_import_export.models.ShippingInformation
        :param delivery_package: Contains information about the package being shipped by the customer
         to the Microsoft data center.
        :type delivery_package: ~storage_import_export.models.PackageInfomation
        :param return_package: Contains information about the package being shipped by the customer to
         the Microsoft data center.
        :type return_package: ~storage_import_export.models.PackageInfomation
        :param diagnostics_path: The virtual blob directory to which the copy logs and backups of drive
         manifest files (if enabled) will be stored.
        :type diagnostics_path: str
        :param log_level: Default value is Error. Indicates whether error logging or verbose logging
         will be enabled.
        :type log_level: str
        :param backup_drive_manifest: Default value is false. Indicates whether the manifest files on
         the drives should be copied to block blobs.
        :type backup_drive_manifest: bool
        :param state: Current state of the job.
        :type state: str
        :param cancel_requested: Indicates whether a request has been submitted to cancel the job.
        :type cancel_requested: bool
        :param percent_complete: Overall percentage completed for the job.
        :type percent_complete: int
        :param incomplete_blob_list_uri: A blob path that points to a block blob containing a list of
         blob names that were not exported due to insufficient drive space. If all blobs were exported
         successfully, then this element is not included in the response.
        :type incomplete_blob_list_uri: str
        :param drive_list: List of up to ten drives that comprise the job. The drive list is a required
         element for an import job; it is not specified for export jobs.
        :type drive_list: list[~storage_import_export.models.DriveStatus]
        :param export: A property containing information about the blobs to be exported for an export
         job. This property is required for export jobs, but must not be specified for import jobs.
        :type export: ~storage_import_export.models.Export
        :param provisioning_state: Specifies the provisioning state of the job.
        :type provisioning_state: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: JobResponse or JobResponse or the result of cls(response)
        :rtype: ~storage_import_export.models.JobResponse or ~storage_import_export.models.JobResponse
        :raises: ~storage_import_export.models.ErrorResponseException:
        """
        cls = kwargs.pop('cls', None )  # type: ClsType["models.JobResponse"]
        error_map = kwargs.pop('error_map', {})

        body = models.PutJobParameters(location=location, tags=tags, storage_account_id=storage_account_id, job_type=job_type, return_address=return_address, return_shipping=return_shipping, shipping_information=shipping_information, delivery_package=delivery_package, return_package=return_package, diagnostics_path=diagnostics_path, log_level=log_level, backup_drive_manifest=backup_drive_manifest, state=state, cancel_requested=cancel_requested, percent_complete=percent_complete, incomplete_blob_list_uri=incomplete_blob_list_uri, drive_list=drive_list, export=export, provisioning_state=provisioning_state)
        api_version = "2016-11-01"

        # Construct URL
        url = self.create.metadata['url']
        path_format_arguments = {
            'jobName': self._serialize.url("job_name", job_name, 'str'),
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

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

        # Construct headers
        header_parameters = {}
        if self._config.acceptlanguage is not None:
            header_parameters['Accept-Language'] = self._serialize.header("self._config.acceptlanguage", self._config.acceptlanguage, 'str')
        if client_tenant_id is not None:
            header_parameters['x-ms-client-tenant-id'] = self._serialize.header("client_tenant_id", client_tenant_id, 'str')
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json'

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

        # Construct and send request
        request = self._client.put(url, query_parameters, header_parameters, body_content)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise models.ErrorResponseException.from_response(response, self._deserialize)

        deserialized = None
        if response.status_code == 200:
            deserialized = self._deserialize('JobResponse', pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize('JobResponse', pipeline_response)

        if cls:
          return cls(pipeline_response, deserialized, {})

        return deserialized
    create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ImportExport/jobs/{jobName}'}

    def delete(
        self,
        job_name,  # type: str
        resource_group_name,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Deletes an existing job. Only jobs in the Creating or Completed states can be deleted.

        :param job_name: The name of the import/export job.
        :type job_name: str
        :param resource_group_name: The resource group name uniquely identifies the resource group
         within the user subscription.
        :type resource_group_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None or the result of cls(response)
        :rtype: None
        :raises: ~storage_import_export.models.ErrorResponseException:
        """
        cls = kwargs.pop('cls', None )  # type: ClsType[None]
        error_map = kwargs.pop('error_map', {})
        api_version = "2016-11-01"

        # Construct URL
        url = self.delete.metadata['url']
        path_format_arguments = {
            'jobName': self._serialize.url("job_name", job_name, 'str'),
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

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

        # Construct headers
        header_parameters = {}
        if self._config.acceptlanguage is not None:
            header_parameters['Accept-Language'] = self._serialize.header("self._config.acceptlanguage", self._config.acceptlanguage, 'str')
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

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

        if cls:
          return cls(pipeline_response, None, {})

    delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ImportExport/jobs/{jobName}'}
