"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from .basesdk import BaseSDK
from datetime import datetime
from enum import Enum
from train_travel import errors, models, utils
from train_travel._hooks import HookContext
from train_travel.types import OptionalNullable, UNSET
from train_travel.utils import get_security_from_env
from train_travel.utils.unmarshal_json_response import unmarshal_json_response
from typing import Mapping, Optional


class GetTripsAcceptEnum(str, Enum):
    APPLICATION_JSON = "application/json"
    APPLICATION_XML = "application/xml"


class Trips(BaseSDK):
    r"""Timetables and routes for train trips between stations, including pricing
    and availability.

    """

    def get_trips(
        self,
        *,
        origin: str,
        destination: str,
        date_: datetime,
        page: Optional[int] = 1,
        limit: Optional[int] = 10,
        bicycles: Optional[bool] = False,
        dogs: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        accept_header_override: Optional[GetTripsAcceptEnum] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.GetTripsResponse:
        r"""Get available train trips

        Returns a list of available train trips between the specified origin and destination stations on the given date, and allows for filtering by bicycle and dog allowances.


        :param origin: The ID of the origin station
        :param destination: The ID of the destination station
        :param date_: The date and time of the trip in ISO 8601 format in origin station's timezone.
        :param page: The page number to return
        :param limit: The number of items to return per page
        :param bicycles: Only return trips where bicycles are known to be allowed
        :param dogs: Only return trips where dogs are known to be allowed
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param accept_header_override: Override the default accept header for this method
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.GetTripsRequest(
            page=page,
            limit=limit,
            origin=origin,
            destination=destination,
            date_=date_,
            bicycles=bicycles,
            dogs=dogs,
        )

        req = self._build_request(
            method="GET",
            path="/trips",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value=accept_header_override.value
            if accept_header_override is not None
            else "application/json;q=1, application/xml;q=0",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="get-trips",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        if utils.match_response(http_res, "200", "application/json"):
            return models.GetTripsResponse(
                result=unmarshal_json_response(models.GetTripsResponseBody, http_res),
                headers=utils.get_response_headers(http_res.headers),
            )
        if utils.match_response(http_res, "200", "application/xml"):
            http_res_bytes = utils.stream_to_bytes(http_res)
            return models.GetTripsResponse(
                result=http_res_bytes,
                headers=utils.get_response_headers(http_res.headers),
            )
        if utils.match_response(http_res, ["400", "401", "403", "429"], "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "500", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )

        raise errors.TrainTravelDefaultError("Unexpected response received", http_res)

    async def get_trips_async(
        self,
        *,
        origin: str,
        destination: str,
        date_: datetime,
        page: Optional[int] = 1,
        limit: Optional[int] = 10,
        bicycles: Optional[bool] = False,
        dogs: Optional[bool] = False,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        accept_header_override: Optional[GetTripsAcceptEnum] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.GetTripsResponse:
        r"""Get available train trips

        Returns a list of available train trips between the specified origin and destination stations on the given date, and allows for filtering by bicycle and dog allowances.


        :param origin: The ID of the origin station
        :param destination: The ID of the destination station
        :param date_: The date and time of the trip in ISO 8601 format in origin station's timezone.
        :param page: The page number to return
        :param limit: The number of items to return per page
        :param bicycles: Only return trips where bicycles are known to be allowed
        :param dogs: Only return trips where dogs are known to be allowed
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param accept_header_override: Override the default accept header for this method
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.GetTripsRequest(
            page=page,
            limit=limit,
            origin=origin,
            destination=destination,
            date_=date_,
            bicycles=bicycles,
            dogs=dogs,
        )

        req = self._build_request_async(
            method="GET",
            path="/trips",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value=accept_header_override.value
            if accept_header_override is not None
            else "application/json;q=1, application/xml;q=0",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config
            else:
                retries = utils.RetryConfig(
                    "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
                )

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["5XX"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="get-trips",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
            retry_config=retry_config,
        )

        if utils.match_response(http_res, "200", "application/json"):
            return models.GetTripsResponse(
                result=unmarshal_json_response(models.GetTripsResponseBody, http_res),
                headers=utils.get_response_headers(http_res.headers),
            )
        if utils.match_response(http_res, "200", "application/xml"):
            http_res_bytes = await utils.stream_to_bytes_async(http_res)
            return models.GetTripsResponse(
                result=http_res_bytes,
                headers=utils.get_response_headers(http_res.headers),
            )
        if utils.match_response(http_res, ["400", "401", "403", "429"], "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "500", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.TrainTravelDefaultError(
                "API error occurred", http_res, http_res_text
            )

        raise errors.TrainTravelDefaultError("Unexpected response received", http_res)
