/*
 * 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_variable`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateVariableError {
    Status400(models::ErrorResponse),
    Status401(models::ErrorResponse),
    Status500(models::ErrorResponse),
    UnknownValue(serde_json::Value),
}

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

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

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

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

/// Create variable (single or bulk).
pub async fn create_variable(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
    inst_id: &str,
    new_variable: Vec<models::NewVariable>,
) -> Result<models::ListVariables200Response, Error<CreateVariableError>> {
    // 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_path_inst_id = inst_id;
    let p_body_new_variable = new_variable;

    let uri_str = format!(
        "{}/v3/streams/projects/{project_id}/sites/{site_id}/instruments/{inst_id}/variables",
        configuration.base_path,
        project_id = crate::apis::urlencode(p_path_project_id),
        site_id = crate::apis::urlencode(p_path_site_id),
        inst_id = crate::apis::urlencode(p_path_inst_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_variable);

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

/// Delete a variable
pub async fn delete_variable(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
    inst_id: &str,
    var_id: &str,
) -> Result<models::GetVariable200Response, Error<DeleteVariableError>> {
    // 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_path_inst_id = inst_id;
    let p_path_var_id = var_id;

    let uri_str = format!("{}/v3/streams/projects/{project_id}/sites/{site_id}/instruments/{inst_id}/variables/{var_id}", configuration.base_path, project_id=crate::apis::urlencode(p_path_project_id), site_id=crate::apis::urlencode(p_path_site_id), inst_id=crate::apis::urlencode(p_path_inst_id), var_id=crate::apis::urlencode(p_path_var_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::GetVariable200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetVariable200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<DeleteVariableError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get details of a specific variable by its id
pub async fn get_variable(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
    inst_id: &str,
    var_id: &str,
) -> Result<models::GetVariable200Response, Error<GetVariableError>> {
    // 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_path_inst_id = inst_id;
    let p_path_var_id = var_id;

    let uri_str = format!("{}/v3/streams/projects/{project_id}/sites/{site_id}/instruments/{inst_id}/variables/{var_id}", configuration.base_path, project_id=crate::apis::urlencode(p_path_project_id), site_id=crate::apis::urlencode(p_path_site_id), inst_id=crate::apis::urlencode(p_path_inst_id), var_id=crate::apis::urlencode(p_path_var_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::GetVariable200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetVariable200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetVariableError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// List variables.
pub async fn list_variables(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
    inst_id: &str,
    query: Option<&str>,
    limit: Option<i32>,
    skip: Option<i32>,
) -> Result<models::ListVariables200Response, Error<ListVariablesError>> {
    // 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_path_inst_id = inst_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/{site_id}/instruments/{inst_id}/variables",
        configuration.base_path,
        project_id = crate::apis::urlencode(p_path_project_id),
        site_id = crate::apis::urlencode(p_path_site_id),
        inst_id = crate::apis::urlencode(p_path_inst_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::ListVariables200Response`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListVariables200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListVariablesError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Update a variable
pub async fn update_variable(
    configuration: &configuration::Configuration,
    project_id: &str,
    site_id: &str,
    inst_id: &str,
    var_id: &str,
    update_variable: models::UpdateVariable,
) -> Result<models::GetVariable200Response, Error<UpdateVariableError>> {
    // 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_path_inst_id = inst_id;
    let p_path_var_id = var_id;
    let p_body_update_variable = update_variable;

    let uri_str = format!("{}/v3/streams/projects/{project_id}/sites/{site_id}/instruments/{inst_id}/variables/{var_id}", configuration.base_path, project_id=crate::apis::urlencode(p_path_project_id), site_id=crate::apis::urlencode(p_path_site_id), inst_id=crate::apis::urlencode(p_path_inst_id), var_id=crate::apis::urlencode(p_path_var_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_variable);

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