/*
 * Tapis Workflows API
 *
 * Create and manage pipelines
 *
 * The version of the OpenAPI document: 1.6.0
 * 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 [`acquire_pipeline_lock`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AcquirePipelineLockError {
    UnknownValue(serde_json::Value),
}

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

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

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

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

/// Attempt to acquire a lock on a Pipeline
pub async fn acquire_pipeline_lock(
    configuration: &configuration::Configuration,
    group_id: &str,
    pipeline_id: &str,
    pipeline_run_uuid: &str,
    req_pipeline_lock: models::ReqPipelineLock,
) -> Result<models::RespPipelineLockAcquisition, Error<AcquirePipelineLockError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_id = group_id;
    let p_path_pipeline_id = pipeline_id;
    let p_path_pipeline_run_uuid = pipeline_run_uuid;
    let p_body_req_pipeline_lock = req_pipeline_lock;

    let uri_str = format!(
        "{}/v3/workflows/groups/{group_id}/pipelines/{pipeline_id}/runs/{pipeline_run_uuid}/locks",
        configuration.base_path,
        group_id = crate::apis::urlencode(p_path_group_id),
        pipeline_id = crate::apis::urlencode(p_path_pipeline_id),
        pipeline_run_uuid = crate::apis::urlencode(p_path_pipeline_run_uuid)
    );
    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());
    }
    if let Some(ref apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-TAPIS-TOKEN", value);
    };
    req_builder = req_builder.json(&p_body_req_pipeline_lock);

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

/// Get a pipeline run
pub async fn get_pipeline_run(
    configuration: &configuration::Configuration,
    group_id: &str,
    pipeline_id: &str,
    pipeline_run_uuid: &str,
) -> Result<models::RespPipelineRun, Error<GetPipelineRunError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_id = group_id;
    let p_path_pipeline_id = pipeline_id;
    let p_path_pipeline_run_uuid = pipeline_run_uuid;

    let uri_str = format!(
        "{}/v3/workflows/groups/{group_id}/pipelines/{pipeline_id}/runs/{pipeline_run_uuid}",
        configuration.base_path,
        group_id = crate::apis::urlencode(p_path_group_id),
        pipeline_id = crate::apis::urlencode(p_path_pipeline_id),
        pipeline_run_uuid = crate::apis::urlencode(p_path_pipeline_run_uuid)
    );
    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());
    }
    if let Some(ref apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-TAPIS-TOKEN", value);
    };

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

/// List runs for a pipeline
pub async fn list_pipeline_runs(
    configuration: &configuration::Configuration,
    group_id: &str,
    pipeline_id: &str,
) -> Result<models::RespPipelineRunList, Error<ListPipelineRunsError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_id = group_id;
    let p_path_pipeline_id = pipeline_id;

    let uri_str = format!(
        "{}/v3/workflows/groups/{group_id}/pipelines/{pipeline_id}/runs",
        configuration.base_path,
        group_id = crate::apis::urlencode(p_path_group_id),
        pipeline_id = crate::apis::urlencode(p_path_pipeline_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());
    }
    if let Some(ref apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-TAPIS-TOKEN", value);
    };

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

/// Terminate a running pipeline
pub async fn terminate_pipeline(
    configuration: &configuration::Configuration,
    group_id: &str,
    pipeline_id: &str,
    pipeline_run_uuid: &str,
) -> Result<models::RespPipelineRun, Error<TerminatePipelineError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_id = group_id;
    let p_path_pipeline_id = pipeline_id;
    let p_path_pipeline_run_uuid = pipeline_run_uuid;

    let uri_str = format!(
        "{}/v3/workflows/groups/{group_id}/pipelines/{pipeline_id}/runs/{pipeline_run_uuid}",
        configuration.base_path,
        group_id = crate::apis::urlencode(p_path_group_id),
        pipeline_id = crate::apis::urlencode(p_path_pipeline_id),
        pipeline_run_uuid = crate::apis::urlencode(p_path_pipeline_run_uuid)
    );
    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());
    }
    if let Some(ref apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-TAPIS-TOKEN", value);
    };

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

/// Endpoints that update pipeline runs are only accessible to the Workflow Executor
pub async fn update_pipeline_run_status(
    configuration: &configuration::Configuration,
    x_workflow_executor_token: &str,
    pipeline_run_uuid: &str,
    status: models::EnumRunStatus,
    req_patch_pipeline_run: Option<models::ReqPatchPipelineRun>,
) -> Result<models::RespString, Error<UpdatePipelineRunStatusError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_header_x_workflow_executor_token = x_workflow_executor_token;
    let p_path_pipeline_run_uuid = pipeline_run_uuid;
    let p_path_status = status;
    let p_body_req_patch_pipeline_run = req_patch_pipeline_run;

    let uri_str = format!(
        "{}/v3/workflows/executor/runs/{pipeline_run_uuid}/{status}",
        configuration.base_path,
        pipeline_run_uuid = crate::apis::urlencode(p_path_pipeline_run_uuid),
        status = p_path_status
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::PATCH, &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.header(
        "X-WORKFLOW-EXECUTOR-TOKEN",
        p_header_x_workflow_executor_token.to_string(),
    );
    if let Some(ref apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-TAPIS-TOKEN", value);
    };
    req_builder = req_builder.json(&p_body_req_patch_pipeline_run);

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