/*
 * Streams API
 *
 * Manage Tapis Streams API.
 *
 * The version of the OpenAPI document: 1
 * Contact: cicsupport@tacc.utexas.edu
 * Generated by: https://openapi-generator.tech
 */

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

/// struct for typed errors of method [`create_site`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateSiteError {
    Status400(models::ErrorResponse),
    Status401(models::ErrorResponse),
    Status500(models::ErrorResponse),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`delete_site`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteSiteError {
    Status400(models::ErrorResponse),
    Status401(models::ErrorResponse),
    Status404(models::ErrorResponse),
    Status500(models::ErrorResponse),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`get_site`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetSiteError {
    Status400(models::ErrorResponse),
    Status401(models::ErrorResponse),
    Status404(models::ErrorResponse),
    Status500(models::ErrorResponse),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`list_sites`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListSitesError {
    Status400(models::ErrorResponse),
    Status401(models::ErrorResponse),
    Status500(models::ErrorResponse),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`update_site`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateSiteError {
    Status400(models::ErrorResponse),
    Status401(models::ErrorResponse),
    Status404(models::ErrorResponse),
    Status500(models::ErrorResponse),
    UnknownValue(serde_json::Value),
}

/// Create a site. (single or bulk)
pub async fn create_site(
    configuration: &configuration::Configuration,
    project_id: &str,
    new_site: Vec<models::NewSite>,
) -> Result<models::ListSites200Response, Error<CreateSiteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_project_id = project_id;
    let p_body_new_site = new_site;

    let uri_str = format!(
        "{}/v3/streams/projects/{project_id}/sites",
        configuration.base_path,
        project_id = crate::apis::urlencode(p_path_project_id)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&p_body_new_site);

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListSites200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListSites200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateSiteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Delete a site
pub async fn delete_site(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
) -> Result<models::GetSite200Response, Error<DeleteSiteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_project_id = project_id;
    let p_path_site_id = site_id;

    let uri_str = format!(
        "{}/v3/streams/projects/{project_id}/sites/{site_id}",
        configuration.base_path,
        project_id = crate::apis::urlencode(p_path_project_id),
        site_id = crate::apis::urlencode(p_path_site_id)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::DELETE, &uri_str);

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetSite200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetSite200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<DeleteSiteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get site details.
pub async fn get_site(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
) -> Result<models::GetSite200Response, Error<GetSiteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_project_id = project_id;
    let p_path_site_id = site_id;

    let uri_str = format!(
        "{}/v3/streams/projects/{project_id}/sites/{site_id}",
        configuration.base_path,
        project_id = crate::apis::urlencode(p_path_project_id),
        site_id = crate::apis::urlencode(p_path_site_id)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetSite200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetSite200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetSiteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// List sites.
pub async fn list_sites(
    configuration: &configuration::Configuration,
    project_id: &str,
    query: Option<&str>,
    limit: Option<i32>,
    skip: Option<i32>,
) -> Result<models::ListSites200Response, Error<ListSitesError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_project_id = project_id;
    let p_query_query = query;
    let p_query_limit = limit;
    let p_query_skip = skip;

    let uri_str = format!(
        "{}/v3/streams/projects/{project_id}/sites",
        configuration.base_path,
        project_id = crate::apis::urlencode(p_path_project_id)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = p_query_query {
        req_builder = req_builder.query(&[("query", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_limit {
        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_skip {
        req_builder = req_builder.query(&[("skip", &param_value.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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListSites200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListSites200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListSitesError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Update a site
pub async fn update_site(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
    update_site: models::UpdateSite,
) -> Result<models::GetSite200Response, Error<UpdateSiteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_project_id = project_id;
    let p_path_site_id = site_id;
    let p_body_update_site = update_site;

    let uri_str = format!(
        "{}/v3/streams/projects/{project_id}/sites/{site_id}",
        configuration.base_path,
        project_id = crate::apis::urlencode(p_path_project_id),
        site_id = crate::apis::urlencode(p_path_site_id)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&p_body_update_site);

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetSite200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetSite200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<UpdateSiteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
