/*
 * doqium - service-data REST API
 *
 * doqium - service-data REST API
 *
 * The version of the OpenAPI document: 1.0
 *
 * Generated by: https://openapi-generator.tech
 */

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

/// struct for typed errors of method [`delete_attachment`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteAttachmentError {
    Status401(models::ErrorModel),
    Status409(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`download_attachment`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DownloadAttachmentError {
    Status401(models::ErrorModel),
    Status404(models::ErrorModel),
    Status409(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

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

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

/// struct for typed errors of method [`update_attachment`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateAttachmentError {
    Status401(models::ErrorModel),
    Status409(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`upload_attachment`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UploadAttachmentError {
    Status400(models::ErrorModel),
    Status401(models::ErrorModel),
    Status402(models::ErrorModel),
    Status409(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

/// Deteles a new note attachment
pub async fn delete_attachment(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
    attachment_id: &str,
) -> Result<serde_json::Value, Error<DeleteAttachmentError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_notebook_id = notebook_id;
    let p_path_note_id = note_id;
    let p_path_attachment_id = attachment_id;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes/{noteId}/attachments/{attachmentId}",
        configuration.base_path,
        notebookId = crate::doqium_data_client::apis::urlencode(p_path_notebook_id),
        noteId = crate::doqium_data_client::apis::urlencode(p_path_note_id),
        attachmentId = crate::doqium_data_client::apis::urlencode(p_path_attachment_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 => return 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) => return 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<DeleteAttachmentError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Retrieves a note's attachment, either as download or to embed
pub async fn download_attachment(
    configuration: &configuration::Configuration,
    username: &str,
    workspace_slug: &str,
    notebook_slug: &str,
    note_slug: &str,
    attachment: &str,
) -> Result<reqwest::Response, Error<DownloadAttachmentError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_username = username;
    let p_path_workspace_slug = workspace_slug;
    let p_path_notebook_slug = notebook_slug;
    let p_path_note_slug = note_slug;
    let p_path_attachment = attachment;

    let uri_str = format!("{}/api/v1/{username}/{workspaceSlug}/{notebookSlug}/notes/{noteSlug}/attachments/{attachment}", configuration.base_path, username=crate::doqium_data_client::apis::urlencode(p_path_username), workspaceSlug=crate::doqium_data_client::apis::urlencode(p_path_workspace_slug), notebookSlug=crate::doqium_data_client::apis::urlencode(p_path_notebook_slug), noteSlug=crate::doqium_data_client::apis::urlencode(p_path_note_slug), attachment=p_path_attachment.to_string());
    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();

    if !status.is_client_error() && !status.is_server_error() {
        Ok(resp)
    } else {
        let content = resp.text().await?;
        let entity: Option<DownloadAttachmentError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Retrieve list of attachments for a given note
pub async fn list_attachments(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
) -> Result<Vec<models::Attachment>, Error<ListAttachmentsError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_notebook_id = notebook_id;
    let p_path_note_id = note_id;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes/{noteId}/attachments",
        configuration.base_path,
        notebookId = crate::doqium_data_client::apis::urlencode(p_path_notebook_id),
        noteId = crate::doqium_data_client::apis::urlencode(p_path_note_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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::Attachment&gt;`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::Attachment&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListAttachmentsError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Retrieve list of attachments for a given public note
pub async fn list_attachments_public_note(
    configuration: &configuration::Configuration,
    username: &str,
    workspace_slug: &str,
    notebook_slug: &str,
    note_slug: &str,
) -> Result<Vec<models::Attachment>, Error<ListAttachmentsPublicNoteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_username = username;
    let p_path_workspace_slug = workspace_slug;
    let p_path_notebook_slug = notebook_slug;
    let p_path_note_slug = note_slug;

    let uri_str = format!(
        "{}/api/v1/{username}/{workspaceSlug}/{notebookSlug}/notes/{noteSlug}/attachments",
        configuration.base_path,
        username = crate::doqium_data_client::apis::urlencode(p_path_username),
        workspaceSlug = crate::doqium_data_client::apis::urlencode(p_path_workspace_slug),
        notebookSlug = crate::doqium_data_client::apis::urlencode(p_path_notebook_slug),
        noteSlug = crate::doqium_data_client::apis::urlencode(p_path_note_slug)
    );
    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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::Attachment&gt;`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::Attachment&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListAttachmentsPublicNoteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Updates an attachment
pub async fn update_attachment(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
    attachment_id: &str,
    update_attachment_request: models::UpdateAttachmentRequest,
) -> Result<models::Attachment, Error<UpdateAttachmentError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_notebook_id = notebook_id;
    let p_path_note_id = note_id;
    let p_path_attachment_id = attachment_id;
    let p_body_update_attachment_request = update_attachment_request;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes/{noteId}/attachments/{attachmentId}",
        configuration.base_path,
        notebookId = crate::doqium_data_client::apis::urlencode(p_path_notebook_id),
        noteId = crate::doqium_data_client::apis::urlencode(p_path_note_id),
        attachmentId = crate::doqium_data_client::apis::urlencode(p_path_attachment_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_attachment_request);

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

/// Creates a new note attachment
pub async fn upload_attachment(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
) -> Result<models::Attachment, Error<UploadAttachmentError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_notebook_id = notebook_id;
    let p_path_note_id = note_id;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes/{noteId}/attachments",
        configuration.base_path,
        notebookId = crate::doqium_data_client::apis::urlencode(p_path_notebook_id),
        noteId = crate::doqium_data_client::apis::urlencode(p_path_note_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());
    }

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