/*
 * MOTIS API
 *
 * This is the MOTIS routing API.  Overview of MOTIS API versions:  MOTIS 0.x - deprecated/discontinued  MOTIS 2.x - current, providing:  * /api/v5/{plan,trip,stoptimes,map/trips} renamed METRO mode to SUBURBAN, AREAL_LIFT to AERIAL_LIFT; since MOTIS 2.5.0 * /api/v4/{plan,trip,stoptimes,map/trips} new displayName property, routeShortName only contains actual route short name from source; since MOTIS 2.2.0 * /api/v3/plan with correct maxTransfers API parameter (transfers actually corresponding to number of changes between transit legs (and not to number of transit legs), i.e. maxTransfers=0 returns direct public transit connections, as expected); since MOTIS 2.0.84  * /api/v2/{plan,trip} returns Google polylines with precision=6; since MOTIS 2.0.60 * /api/v1/{plan,trip} returns Google polylines with precision=7 (not defined for |longitude|>107) * /api/v1/_* all other endpoints  If you use the JS client lib https://www.npmjs.com/package/@motis-project/motis-client, endpoint versions will be taken into account automatically (i.e. the newest one available will be used). 
 *
 * The version of the OpenAPI document: v5
 * Contact: felix@triptix.tech
 * Generated by: https://openapi-generator.tech
 */


use reqwest;
use serde::{Deserialize, Serialize, de::Error as _};
use crate::{apis::ResponseContent, models};
use super::{Error, configuration, ContentType};


/// struct for typed errors of method [`stoptimes`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum StoptimesError {
    Status400(models::Error),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`trip`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TripError {
    Status400(models::Error),
    UnknownValue(serde_json::Value),
}


pub async fn stoptimes(configuration: &configuration::Configuration, stop_id: &str, n: i32, time: Option<String>, arrive_by: Option<bool>, direction: Option<&str>, mode: Option<Vec<models::Mode>>, radius: Option<i32>, exact_radius: Option<bool>, fetch_stops: Option<bool>, page_cursor: Option<&str>, with_scheduled_skipped_stops: Option<bool>, language: Option<Vec<String>>) -> Result<models::Stoptimes200Response, Error<StoptimesError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_stop_id = stop_id;
    let p_query_n = n;
    let p_query_time = time;
    let p_query_arrive_by = arrive_by;
    let p_query_direction = direction;
    let p_query_mode = mode;
    let p_query_radius = radius;
    let p_query_exact_radius = exact_radius;
    let p_query_fetch_stops = fetch_stops;
    let p_query_page_cursor = page_cursor;
    let p_query_with_scheduled_skipped_stops = with_scheduled_skipped_stops;
    let p_query_language = language;

    let uri_str = format!("{}/api/v5/stoptimes", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    req_builder = req_builder.query(&[("stopId", &p_query_stop_id.to_string())]);
    if let Some(ref param_value) = p_query_time {
        req_builder = req_builder.query(&[("time", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_arrive_by {
        req_builder = req_builder.query(&[("arriveBy", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_direction {
        req_builder = req_builder.query(&[("direction", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_mode {
        req_builder = match "csv" {
            "multi" => req_builder.query(&param_value.into_iter().map(|p| ("mode".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
            _ => req_builder.query(&[("mode", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
        };
    }
    req_builder = req_builder.query(&[("n", &p_query_n.to_string())]);
    if let Some(ref param_value) = p_query_radius {
        req_builder = req_builder.query(&[("radius", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_exact_radius {
        req_builder = req_builder.query(&[("exactRadius", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_fetch_stops {
        req_builder = req_builder.query(&[("fetchStops", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_page_cursor {
        req_builder = req_builder.query(&[("pageCursor", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_with_scheduled_skipped_stops {
        req_builder = req_builder.query(&[("withScheduledSkippedStops", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_language {
        req_builder = match "csv" {
            "multi" => req_builder.query(&param_value.into_iter().map(|p| ("language".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
            _ => req_builder.query(&[("language", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
        };
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Stoptimes200Response`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Stoptimes200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<StoptimesError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

pub async fn trip(configuration: &configuration::Configuration, trip_id: &str, with_scheduled_skipped_stops: Option<bool>, join_interlined_legs: Option<bool>, language: Option<Vec<String>>) -> Result<models::Itinerary, Error<TripError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_trip_id = trip_id;
    let p_query_with_scheduled_skipped_stops = with_scheduled_skipped_stops;
    let p_query_join_interlined_legs = join_interlined_legs;
    let p_query_language = language;

    let uri_str = format!("{}/api/v5/trip", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    req_builder = req_builder.query(&[("tripId", &p_query_trip_id.to_string())]);
    if let Some(ref param_value) = p_query_with_scheduled_skipped_stops {
        req_builder = req_builder.query(&[("withScheduledSkippedStops", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_join_interlined_legs {
        req_builder = req_builder.query(&[("joinInterlinedLegs", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_language {
        req_builder = match "csv" {
            "multi" => req_builder.query(&param_value.into_iter().map(|p| ("language".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
            _ => req_builder.query(&[("language", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
        };
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Itinerary`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Itinerary`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<TripError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

