/*
 * 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 [`create_task_execution`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateTaskExecutionError {
    UnknownValue(serde_json::Value),
}

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

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

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

/// Create a task execution
pub async fn create_task_execution(
    configuration: &configuration::Configuration,
    x_workflow_executor_token: &str,
    pipeline_run_uuid: &str,
    req_create_task_execution: models::ReqCreateTaskExecution,
) -> Result<models::RespResourceUrl, Error<CreateTaskExecutionError>> {
    // 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_body_req_create_task_execution = req_create_task_execution;

    let uri_str = format!(
        "{}/v3/workflows/executor/runs/{pipeline_run_uuid}/executions",
        configuration.base_path,
        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());
    }
    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_create_task_execution);

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

/// Get a Task Execution
pub async fn get_task_execution(
    configuration: &configuration::Configuration,
    group_id: &str,
    pipeline_id: &str,
    pipeline_run_uuid: &str,
    task_execution_uuid: &str,
) -> Result<models::RespTaskExecution, Error<GetTaskExecutionError>> {
    // 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_path_task_execution_uuid = task_execution_uuid;

    let uri_str = format!("{}/v3/workflows/groups/{group_id}/pipelines/{pipeline_id}/runs/{pipeline_run_uuid}/executions/{task_execution_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), task_execution_uuid=crate::apis::urlencode(p_path_task_execution_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::RespTaskExecution`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::RespTaskExecution`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetTaskExecutionError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// List Task Executions for a pipeline run
pub async fn list_task_executions(
    configuration: &configuration::Configuration,
    group_id: &str,
    pipeline_id: &str,
    pipeline_run_uuid: &str,
) -> Result<models::RespTaskExecutionList, Error<ListTaskExecutionsError>> {
    // 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}/executions", 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::RespTaskExecutionList`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::RespTaskExecutionList`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListTaskExecutionsError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// update a task execution status
pub async fn update_task_execution_status(
    configuration: &configuration::Configuration,
    x_workflow_executor_token: &str,
    task_execution_uuid: &str,
    status: models::EnumRunStatus,
    req_patch_task_execution: Option<models::ReqPatchTaskExecution>,
) -> Result<models::RespString, Error<UpdateTaskExecutionStatusError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_header_x_workflow_executor_token = x_workflow_executor_token;
    let p_path_task_execution_uuid = task_execution_uuid;
    let p_path_status = status;
    let p_body_req_patch_task_execution = req_patch_task_execution;

    let uri_str = format!(
        "{}/v3/workflows/executor/executions/{task_execution_uuid}/{status}",
        configuration.base_path,
        task_execution_uuid = crate::apis::urlencode(p_path_task_execution_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_task_execution);

    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<UpdateTaskExecutionStatusError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
