# 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 collections.abc import MutableMapping
from io import IOBase
from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload
import urllib.parse

from azure.core import PipelineClient
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.rest import HttpRequest, HttpResponse
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict

from .. import models as _models
from .._configuration import AzureDigitalTwinsAPIConfiguration
from .._utils.serialization import Deserializer, Serializer

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

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False


def build_list_request(
    *,
    traceparent: Optional[str] = None,
    tracestate: Optional[str] = None,
    max_items_per_page: Optional[int] = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-31"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/jobs/imports")

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if traceparent is not None:
        _headers["traceparent"] = _SERIALIZER.header("traceparent", traceparent, "str")
    if tracestate is not None:
        _headers["tracestate"] = _SERIALIZER.header("tracestate", tracestate, "str")
    if max_items_per_page is not None:
        _headers["max-items-per-page"] = _SERIALIZER.header("max_items_per_page", max_items_per_page, "int")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_add_request(
    id: str, *, traceparent: Optional[str] = None, tracestate: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-31"))
    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/jobs/imports/{id}")
    path_format_arguments = {
        "id": _SERIALIZER.url("id", id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if traceparent is not None:
        _headers["traceparent"] = _SERIALIZER.header("traceparent", traceparent, "str")
    if tracestate is not None:
        _headers["tracestate"] = _SERIALIZER.header("tracestate", tracestate, "str")
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)


def build_get_by_id_request(
    id: str, *, traceparent: Optional[str] = None, tracestate: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-31"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/jobs/imports/{id}")
    path_format_arguments = {
        "id": _SERIALIZER.url("id", id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if traceparent is not None:
        _headers["traceparent"] = _SERIALIZER.header("traceparent", traceparent, "str")
    if tracestate is not None:
        _headers["tracestate"] = _SERIALIZER.header("tracestate", tracestate, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_delete_request(
    id: str, *, traceparent: Optional[str] = None, tracestate: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-31"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/jobs/imports/{id}")
    path_format_arguments = {
        "id": _SERIALIZER.url("id", id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if traceparent is not None:
        _headers["traceparent"] = _SERIALIZER.header("traceparent", traceparent, "str")
    if tracestate is not None:
        _headers["tracestate"] = _SERIALIZER.header("tracestate", tracestate, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)


def build_cancel_request(
    id: str, *, traceparent: Optional[str] = None, tracestate: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-10-31"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/jobs/imports/{id}/cancel")
    path_format_arguments = {
        "id": _SERIALIZER.url("id", id, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if traceparent is not None:
        _headers["traceparent"] = _SERIALIZER.header("traceparent", traceparent, "str")
    if tracestate is not None:
        _headers["tracestate"] = _SERIALIZER.header("tracestate", tracestate, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


class ImportJobsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.digitaltwins.core.AzureDigitalTwinsAPI`'s
        :attr:`import_jobs` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config: AzureDigitalTwinsAPIConfiguration = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self, import_jobs_list_options: Optional[_models.ImportJobsListOptions] = None, **kwargs: Any
    ) -> ItemPaged["_models.ImportJob"]:
        """Retrieves all import jobs.
        Status codes:


        * 200 OK.

        :param import_jobs_list_options: Parameter group. Default value is None.
        :type import_jobs_list_options: ~azure.digitaltwins.core.models.ImportJobsListOptions
        :return: An iterator like instance of either ImportJob or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.digitaltwins.core.models.ImportJob]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[_models.ImportJobCollection] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:
                _traceparent = None
                _tracestate = None
                _max_items_per_page = None
                if import_jobs_list_options is not None:
                    _max_items_per_page = import_jobs_list_options.max_items_per_page
                    _traceparent = import_jobs_list_options.traceparent
                    _tracestate = import_jobs_list_options.tracestate

                _request = build_list_request(
                    traceparent=_traceparent,
                    tracestate=_tracestate,
                    max_items_per_page=_max_items_per_page,
                    api_version=api_version,
                    headers=_headers,
                    params=_params,
                )
                _request.url = self._client.format_url(_request.url)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                _request.url = self._client.format_url(_request.url)
                _request.method = "GET"
            return _request

        def extract_data(pipeline_response):
            deserialized = self._deserialize("ImportJobCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.next_link or None, iter(list_of_elem)

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

            _stream = False
            pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **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)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error)

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    @overload
    def add(
        self,
        id: str,
        import_job: _models.ImportJob,
        import_jobs_add_options: Optional[_models.ImportJobsAddOptions] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ImportJob:
        """Creates an import job.
        Status codes:


        * 201 Created
        * 400 Bad Request

          * JobLimitReached - The maximum number of import jobs allowed has been reached.
          * ValidationFailed - The import job request is not valid.

        :param id: The id for the import job. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param import_job: The import job being added. Required.
        :type import_job: ~azure.digitaltwins.core.models.ImportJob
        :param import_jobs_add_options: Parameter group. Default value is None.
        :type import_jobs_add_options: ~azure.digitaltwins.core.models.ImportJobsAddOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ImportJob or the result of cls(response)
        :rtype: ~azure.digitaltwins.core.models.ImportJob
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def add(
        self,
        id: str,
        import_job: IO[bytes],
        import_jobs_add_options: Optional[_models.ImportJobsAddOptions] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ImportJob:
        """Creates an import job.
        Status codes:


        * 201 Created
        * 400 Bad Request

          * JobLimitReached - The maximum number of import jobs allowed has been reached.
          * ValidationFailed - The import job request is not valid.

        :param id: The id for the import job. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param import_job: The import job being added. Required.
        :type import_job: IO[bytes]
        :param import_jobs_add_options: Parameter group. Default value is None.
        :type import_jobs_add_options: ~azure.digitaltwins.core.models.ImportJobsAddOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ImportJob or the result of cls(response)
        :rtype: ~azure.digitaltwins.core.models.ImportJob
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def add(
        self,
        id: str,
        import_job: Union[_models.ImportJob, IO[bytes]],
        import_jobs_add_options: Optional[_models.ImportJobsAddOptions] = None,
        **kwargs: Any
    ) -> _models.ImportJob:
        """Creates an import job.
        Status codes:


        * 201 Created
        * 400 Bad Request

          * JobLimitReached - The maximum number of import jobs allowed has been reached.
          * ValidationFailed - The import job request is not valid.

        :param id: The id for the import job. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param import_job: The import job being added. Is either a ImportJob type or a IO[bytes] type.
         Required.
        :type import_job: ~azure.digitaltwins.core.models.ImportJob or IO[bytes]
        :param import_jobs_add_options: Parameter group. Default value is None.
        :type import_jobs_add_options: ~azure.digitaltwins.core.models.ImportJobsAddOptions
        :return: ImportJob or the result of cls(response)
        :rtype: ~azure.digitaltwins.core.models.ImportJob
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.ImportJob] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if import_jobs_add_options is not None:
            _traceparent = import_jobs_add_options.traceparent
            _tracestate = import_jobs_add_options.tracestate
        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(import_job, (IOBase, bytes)):
            _content = import_job
        else:
            _json = self._serialize.body(import_job, "ImportJob")

        _request = build_add_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

        _stream = False
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize("ImportJob", pipeline_response.http_response)

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def get_by_id(
        self, id: str, import_jobs_get_by_id_options: Optional[_models.ImportJobsGetByIdOptions] = None, **kwargs: Any
    ) -> _models.ImportJob:
        """Retrieves an import job.
        Status codes:


        * 200 OK
        * 404 Not Found

          * ImportJobNotFound - The import job was not found.

        :param id: The id for the import job. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param import_jobs_get_by_id_options: Parameter group. Default value is None.
        :type import_jobs_get_by_id_options: ~azure.digitaltwins.core.models.ImportJobsGetByIdOptions
        :return: ImportJob or the result of cls(response)
        :rtype: ~azure.digitaltwins.core.models.ImportJob
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[_models.ImportJob] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if import_jobs_get_by_id_options is not None:
            _traceparent = import_jobs_get_by_id_options.traceparent
            _tracestate = import_jobs_get_by_id_options.tracestate

        _request = build_get_by_id_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

        _stream = False
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize("ImportJob", pipeline_response.http_response)

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def delete(  # pylint: disable=inconsistent-return-statements
        self, id: str, import_jobs_delete_options: Optional[_models.ImportJobsDeleteOptions] = None, **kwargs: Any
    ) -> None:
        """Deletes an import job. This is simply used to remove a job id, so it may be reused later. It
        can not be used to stop entities from being imported.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * ValidationFailed - The import job request is not valid.

        :param id: The id for the import job. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param import_jobs_delete_options: Parameter group. Default value is None.
        :type import_jobs_delete_options: ~azure.digitaltwins.core.models.ImportJobsDeleteOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if import_jobs_delete_options is not None:
            _traceparent = import_jobs_delete_options.traceparent
            _tracestate = import_jobs_delete_options.tracestate

        _request = build_delete_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

        _stream = False
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore

    @distributed_trace
    def cancel(
        self, id: str, import_jobs_cancel_options: Optional[_models.ImportJobsCancelOptions] = None, **kwargs: Any
    ) -> _models.ImportJob:
        """Cancels an import job that is currently running. Service will stop any import operations
        triggered by the current import job that are in progress, and go to a cancelled state. Please
        note that this will leave your instance in an unknown state as there won't be any rollback
        operation.
        Status codes:


        * 200 Request Accepted
        * 400 Bad Request

          * ValidationFailed - The import job request is not valid.

        :param id: The id for the import job. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param import_jobs_cancel_options: Parameter group. Default value is None.
        :type import_jobs_cancel_options: ~azure.digitaltwins.core.models.ImportJobsCancelOptions
        :return: ImportJob or the result of cls(response)
        :rtype: ~azure.digitaltwins.core.models.ImportJob
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[_models.ImportJob] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if import_jobs_cancel_options is not None:
            _traceparent = import_jobs_cancel_options.traceparent
            _tracestate = import_jobs_cancel_options.tracestate

        _request = build_cancel_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

        _stream = False
        pipeline_response: PipelineResponse = self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize("ImportJob", pipeline_response.http_response)

        if cls:
            return cls(pipeline_response, deserialized, {})  # type: ignore

        return deserialized  # type: ignore
