# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.bad_gateway_error import BadGatewayError
from ..errors.gateway_timeout_error import GatewayTimeoutError
from ..errors.internal_server_error import InternalServerError
from ..errors.method_not_allowed_error import MethodNotAllowedError
from ..errors.not_found_error import NotFoundError
from ..errors.not_implemented_error import NotImplementedError
from ..errors.service_unavailable_error import ServiceUnavailableError
from ..errors.too_many_requests_error import TooManyRequestsError
from ..errors.unauthorized_error import UnauthorizedError
from ..types.advanced_idling_get_idling_events_response_body import AdvancedIdlingGetIdlingEventsResponseBody
from .types.get_idling_events_request_pto_state import GetIdlingEventsRequestPtoState


class RawIdlingClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def get_idling_events(
        self,
        *,
        start_time: str,
        end_time: str,
        asset_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        operator_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        pto_state: typing.Optional[GetIdlingEventsRequestPtoState] = None,
        min_air_temperature_millicelsius: typing.Optional[int] = None,
        max_air_temperature_millicelsius: typing.Optional[int] = None,
        exclude_events_with_unknown_air_temperature: typing.Optional[bool] = None,
        min_duration_milliseconds: typing.Optional[int] = None,
        max_duration_milliseconds: typing.Optional[int] = None,
        tag_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        parent_tag_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        include_external_ids: typing.Optional[bool] = None,
        after: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[AdvancedIdlingGetIdlingEventsResponseBody]:
        """
        Get idling events for the requested time duration.

        **Note:** The data from this endpoint comes from the new Advanced Idling Report, which provides additional data fields for each idling event such as air temperature, geofence, PTO state and minimum idle time. This endpoint includes data from January 1, 2024. If you require additional historical data, you can access it via the [vehicle idling reports API](https://developers.samsara.com/reference/getvehicleidlingreports).

         <b>Rate limit:</b> 5 requests/sec (learn more about rate limits <a href="https://developers.samsara.com/docs/rate-limits" target="_blank">here</a>).

        To use this endpoint, select **Read Idling** under the Fuel & Energy category when creating or editing an API token. <a href="https://developers.samsara.com/docs/authentication#scopes-for-api-tokens" target="_blank">Learn More.</a>


         **Submit Feedback**: Likes, dislikes, and API feature requests should be filed as feedback in our <a href="https://forms.gle/zkD4NCH7HjKb7mm69" target="_blank">API feedback form</a>. If you encountered an issue or noticed inaccuracies in the API documentation, please <a href="https://www.samsara.com/help" target="_blank">submit a case</a> to our support team.

        Parameters
        ----------
        start_time : str
            The start of the time range for filtering idling events in RFC 3339 format. Millisecond precision and timezones are supported. (Examples: 2019-06-11T19:00:00Z, 2015-09-12T14:00:00-04:00). Returns events that begin at or after this timestamp.

        end_time : str
            The end of the time range for filtering idling events in RFC 3339 format. Millisecond precision and timezones are supported. (Examples: 2019-06-13T19:00:00Z, 2015-09-15T14:00:00-04:00). Returns events that begin before this timestamp.

        asset_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of asset IDs. Asset IDs only include vehicle IDs at this time.

        operator_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of operator IDs. Operator IDs only include driver IDs at this time.

        pto_state : typing.Optional[GetIdlingEventsRequestPtoState]
            A filter on the data on this PTO (Power Take-Off) state. If no specific state is provided, data including any state will be included.  Valid values: `active`, `inactive`

        min_air_temperature_millicelsius : typing.Optional[int]
            A filter on the data based on the minimum value of air temperature in millicelsius. The acceptable range for this value is between -20,000 and 50,000 millicelsius.

        max_air_temperature_millicelsius : typing.Optional[int]
            A filter on the data based on the maximum value of air temperature in millicelsius. The acceptable range for this value is between -20,000 and 50,000 millicelsius.

        exclude_events_with_unknown_air_temperature : typing.Optional[bool]
            A filter on the data based on unknown air temperature value.

        min_duration_milliseconds : typing.Optional[int]
            A filter on the data based on the minimum value of Idling duration in milliseconds. The acceptable range for this value is between 2 minutes and 24 hours.

        max_duration_milliseconds : typing.Optional[int]
            A filter on the data based on the maximum value of Idling duration in milliseconds. The acceptable range for this value is between 2 minutes and 24 hours.

        tag_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of tag IDs. Tag IDs only include vehicle IDs at this time.

        parent_tag_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of parent tag IDs. Parent tag IDs only include vehicle IDs at this time.

        include_external_ids : typing.Optional[bool]
            Optional boolean indicating whether to return external IDs on supported entities

        after : typing.Optional[str]
             If specified, this should be the endCursor value from the previous page of results. When present, this request will return the next page of results that occur immediately after the previous page of results.

        limit : typing.Optional[int]
            The limit for how many objects will be in the response. Default and max for this value is 200 objects.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[AdvancedIdlingGetIdlingEventsResponseBody]
            OK response.
        """
        _response = self._client_wrapper.httpx_client.request(
            "idling/events",
            method="GET",
            params={
                "startTime": start_time,
                "endTime": end_time,
                "assetIds": asset_ids,
                "operatorIds": operator_ids,
                "ptoState": pto_state,
                "minAirTemperatureMillicelsius": min_air_temperature_millicelsius,
                "maxAirTemperatureMillicelsius": max_air_temperature_millicelsius,
                "excludeEventsWithUnknownAirTemperature": exclude_events_with_unknown_air_temperature,
                "minDurationMilliseconds": min_duration_milliseconds,
                "maxDurationMilliseconds": max_duration_milliseconds,
                "tagIds": tag_ids,
                "parentTagIds": parent_tag_ids,
                "includeExternalIds": include_external_ids,
                "after": after,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AdvancedIdlingGetIdlingEventsResponseBody,
                    parse_obj_as(
                        type_=AdvancedIdlingGetIdlingEventsResponseBody,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 501:
                raise NotImplementedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 502:
                raise BadGatewayError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 504:
                raise GatewayTimeoutError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawIdlingClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def get_idling_events(
        self,
        *,
        start_time: str,
        end_time: str,
        asset_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        operator_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        pto_state: typing.Optional[GetIdlingEventsRequestPtoState] = None,
        min_air_temperature_millicelsius: typing.Optional[int] = None,
        max_air_temperature_millicelsius: typing.Optional[int] = None,
        exclude_events_with_unknown_air_temperature: typing.Optional[bool] = None,
        min_duration_milliseconds: typing.Optional[int] = None,
        max_duration_milliseconds: typing.Optional[int] = None,
        tag_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        parent_tag_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        include_external_ids: typing.Optional[bool] = None,
        after: typing.Optional[str] = None,
        limit: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AdvancedIdlingGetIdlingEventsResponseBody]:
        """
        Get idling events for the requested time duration.

        **Note:** The data from this endpoint comes from the new Advanced Idling Report, which provides additional data fields for each idling event such as air temperature, geofence, PTO state and minimum idle time. This endpoint includes data from January 1, 2024. If you require additional historical data, you can access it via the [vehicle idling reports API](https://developers.samsara.com/reference/getvehicleidlingreports).

         <b>Rate limit:</b> 5 requests/sec (learn more about rate limits <a href="https://developers.samsara.com/docs/rate-limits" target="_blank">here</a>).

        To use this endpoint, select **Read Idling** under the Fuel & Energy category when creating or editing an API token. <a href="https://developers.samsara.com/docs/authentication#scopes-for-api-tokens" target="_blank">Learn More.</a>


         **Submit Feedback**: Likes, dislikes, and API feature requests should be filed as feedback in our <a href="https://forms.gle/zkD4NCH7HjKb7mm69" target="_blank">API feedback form</a>. If you encountered an issue or noticed inaccuracies in the API documentation, please <a href="https://www.samsara.com/help" target="_blank">submit a case</a> to our support team.

        Parameters
        ----------
        start_time : str
            The start of the time range for filtering idling events in RFC 3339 format. Millisecond precision and timezones are supported. (Examples: 2019-06-11T19:00:00Z, 2015-09-12T14:00:00-04:00). Returns events that begin at or after this timestamp.

        end_time : str
            The end of the time range for filtering idling events in RFC 3339 format. Millisecond precision and timezones are supported. (Examples: 2019-06-13T19:00:00Z, 2015-09-15T14:00:00-04:00). Returns events that begin before this timestamp.

        asset_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of asset IDs. Asset IDs only include vehicle IDs at this time.

        operator_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of operator IDs. Operator IDs only include driver IDs at this time.

        pto_state : typing.Optional[GetIdlingEventsRequestPtoState]
            A filter on the data on this PTO (Power Take-Off) state. If no specific state is provided, data including any state will be included.  Valid values: `active`, `inactive`

        min_air_temperature_millicelsius : typing.Optional[int]
            A filter on the data based on the minimum value of air temperature in millicelsius. The acceptable range for this value is between -20,000 and 50,000 millicelsius.

        max_air_temperature_millicelsius : typing.Optional[int]
            A filter on the data based on the maximum value of air temperature in millicelsius. The acceptable range for this value is between -20,000 and 50,000 millicelsius.

        exclude_events_with_unknown_air_temperature : typing.Optional[bool]
            A filter on the data based on unknown air temperature value.

        min_duration_milliseconds : typing.Optional[int]
            A filter on the data based on the minimum value of Idling duration in milliseconds. The acceptable range for this value is between 2 minutes and 24 hours.

        max_duration_milliseconds : typing.Optional[int]
            A filter on the data based on the maximum value of Idling duration in milliseconds. The acceptable range for this value is between 2 minutes and 24 hours.

        tag_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of tag IDs. Tag IDs only include vehicle IDs at this time.

        parent_tag_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            A filter on the data based on this comma-separated list of parent tag IDs. Parent tag IDs only include vehicle IDs at this time.

        include_external_ids : typing.Optional[bool]
            Optional boolean indicating whether to return external IDs on supported entities

        after : typing.Optional[str]
             If specified, this should be the endCursor value from the previous page of results. When present, this request will return the next page of results that occur immediately after the previous page of results.

        limit : typing.Optional[int]
            The limit for how many objects will be in the response. Default and max for this value is 200 objects.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[AdvancedIdlingGetIdlingEventsResponseBody]
            OK response.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "idling/events",
            method="GET",
            params={
                "startTime": start_time,
                "endTime": end_time,
                "assetIds": asset_ids,
                "operatorIds": operator_ids,
                "ptoState": pto_state,
                "minAirTemperatureMillicelsius": min_air_temperature_millicelsius,
                "maxAirTemperatureMillicelsius": max_air_temperature_millicelsius,
                "excludeEventsWithUnknownAirTemperature": exclude_events_with_unknown_air_temperature,
                "minDurationMilliseconds": min_duration_milliseconds,
                "maxDurationMilliseconds": max_duration_milliseconds,
                "tagIds": tag_ids,
                "parentTagIds": parent_tag_ids,
                "includeExternalIds": include_external_ids,
                "after": after,
                "limit": limit,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AdvancedIdlingGetIdlingEventsResponseBody,
                    parse_obj_as(
                        type_=AdvancedIdlingGetIdlingEventsResponseBody,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 401:
                raise UnauthorizedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 429:
                raise TooManyRequestsError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 500:
                raise InternalServerError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 501:
                raise NotImplementedError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 502:
                raise BadGatewayError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 503:
                raise ServiceUnavailableError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 504:
                raise GatewayTimeoutError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
