/*
 * Tapis Pods Service
 *
 *  The Pods Service is a web service and distributed computing platform providing pods-as-a-service (PaaS). The service  implements a message broker and processor model that requests pods, alongside a health module to poll for pod data, including logs, status, and health. The primary use of this service is to have quick to deploy long-lived services based on Docker images that are exposed via HTTP or TCP endpoints listed by the API.  **The Pods service provides functionality for two types of pod solutions:**  * **Templated Pods** for run-as-is popular images. Neo4J is one example, the template manages TCP ports, user creation, and permissions.  * **Custom Pods** for arbitrary docker images with less functionality. In this case we will expose port 5000 and do nothing else.   The live-docs act as the most up-to-date API reference. Visit the [documentation for more information](https://tapis.readthedocs.io/en/latest/technical/pods.html).
 *
 * The version of the OpenAPI document: 26Q1.1
 * Contact: cicsupport@tacc.utexas.edu
 * Generated by: https://openapi-generator.tech
 */

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

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

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

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

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

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

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

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

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

/// Create a snapshot with inputted information.  Notes: - Author will be given ADMIN level permissions to the snapshot.  Returns new snapshot object.
pub async fn create_snapshot(
    configuration: &configuration::Configuration,
    new_snapshot: models::NewSnapshot,
) -> Result<models::SnapshotResponse, Error<CreateSnapshotError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_new_snapshot = new_snapshot;

    let uri_str = format!("{}/pods/snapshots", configuration.base_path);
    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_snapshot);

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

/// Delete a snapshot.  Returns \"\".
pub async fn delete_snapshot(
    configuration: &configuration::Configuration,
    snapshot_id: &str,
) -> Result<models::DeleteSnapshotResponse, Error<DeleteSnapshotError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_snapshot_id = snapshot_id;

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

/// Download a specific file from a Tapis Snapshot.  Efficiently handles large files (100MB - 10GB) from NFS-backed storage by streaming in chunks.  Note: - This endpoint is for downloading individual files - For directories, use get_snapshot_contents with zip=true - Path cannot be empty or / to prevent downloading entire snapshot
pub async fn download_snapshot_file(
    configuration: &configuration::Configuration,
    snapshot_id: &str,
    path: &str,
) -> Result<serde_json::Value, Error<DownloadSnapshotFileError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_snapshot_id = snapshot_id;
    let p_path_path = path;

    let uri_str = format!(
        "{}/pods/snapshots/{snapshot_id}/download/{path}",
        configuration.base_path,
        snapshot_id = crate::apis::urlencode(p_path_snapshot_id),
        path = crate::apis::urlencode(p_path_path)
    );
    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 `serde_json::Value`",
            ))),
            ContentType::Unsupported(unknown_type) => {
                Err(Error::from(serde_json::Error::custom(format!(
                    "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`"
                ))))
            }
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<DownloadSnapshotFileError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get a snapshot.  Returns retrieved snapshot object.
pub async fn get_snapshot(
    configuration: &configuration::Configuration,
    snapshot_id: &str,
) -> Result<models::SnapshotResponse, Error<GetSnapshotError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_snapshot_id = snapshot_id;

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

/// Get file or directory contents as a stream of data from a Tapis Snapshot.  Use the **zip** query parameter to request directories as a zip archive. This is not allowed if path would result in all files in the snapshot being included. Please download individual directories, files or objects.
pub async fn get_snapshot_contents(
    configuration: &configuration::Configuration,
    snapshot_id: &str,
    path: &str,
    zip: Option<bool>,
) -> Result<serde_json::Value, Error<GetSnapshotContentsError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_snapshot_id = snapshot_id;
    let p_path_path = path;
    let p_query_zip = zip;

    let uri_str = format!(
        "{}/pods/snapshots/{snapshot_id}/contents/{path}",
        configuration.base_path,
        snapshot_id = crate::apis::urlencode(p_path_snapshot_id),
        path = crate::apis::urlencode(p_path_path)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = p_query_zip {
        req_builder = req_builder.query(&[("zip", &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 `serde_json::Value`",
            ))),
            ContentType::Unsupported(unknown_type) => {
                Err(Error::from(serde_json::Error::custom(format!(
                    "Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`"
                ))))
            }
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetSnapshotContentsError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// List files in snapshot.
pub async fn list_snapshot_files(
    configuration: &configuration::Configuration,
    snapshot_id: &str,
) -> Result<models::FilesListResponse, Error<ListSnapshotFilesError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_snapshot_id = snapshot_id;

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

/// Get all snapshots in your respective tenant and site that you have READ or higher access to.  Returns a list of snapshots.
pub async fn list_snapshots(
    configuration: &configuration::Configuration,
) -> Result<models::SnapshotsResponse, Error<ListSnapshotsError>> {
    let uri_str = format!("{}/pods/snapshots", configuration.base_path);
    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::SnapshotsResponse`",
            ))),
            ContentType::Unsupported(unknown_type) => {
                Err(Error::from(serde_json::Error::custom(format!(
                    "Received `{unknown_type}` content type response that cannot be converted to `models::SnapshotsResponse`"
                ))))
            }
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListSnapshotsError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Update a snapshot.  Note: - Fields that change snapshot source or sink are not modifiable. Please recreate your snapshot in that case.  Returns updated snapshot object.
pub async fn update_snapshot(
    configuration: &configuration::Configuration,
    snapshot_id: &str,
    update_snapshot: models::UpdateSnapshot,
) -> Result<models::SnapshotResponse, Error<UpdateSnapshotError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_snapshot_id = snapshot_id;
    let p_body_update_snapshot = update_snapshot;

    let uri_str = format!(
        "{}/pods/snapshots/{snapshot_id}",
        configuration.base_path,
        snapshot_id = p_path_snapshot_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_snapshot);

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