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

/// struct for typed errors of method [`delete_note`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteNoteError {
    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 [`get_note`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetNoteError {
    Status401(models::ErrorModel),
    Status404(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

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

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

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

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

/// Creates a new note in an existing notebook
pub async fn create_note(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_request: models::NoteRequest,
) -> Result<models::CreateNote200Response, Error<CreateNoteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_notebook_id = notebook_id;
    let p_body_note_request = note_request;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes",
        configuration.base_path,
        notebookId = crate::doqium_data_client::apis::urlencode(p_path_notebook_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_note_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::CreateNote200Response`"))),
            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::CreateNote200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateNoteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Permanently delete a note from the system
pub async fn delete_note(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
) -> Result<serde_json::Value, Error<DeleteNoteError>> {
    // 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}",
        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::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<DeleteNoteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Returns the full detail of an existing note
pub async fn get_note(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
) -> Result<models::Note, Error<GetNoteError>> {
    // 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}",
        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 `models::Note`"))),
            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::Note`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetNoteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Returns the list of notes that a notebook contains
pub async fn list_notes(
    configuration: &configuration::Configuration,
    notebook_id: &str,
) -> Result<Vec<models::Note>, Error<ListNotesError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_notebook_id = notebook_id;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes",
        configuration.base_path,
        notebookId = crate::doqium_data_client::apis::urlencode(p_path_notebook_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::Note&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::Note&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListNotesError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Move a note from a notebook (ID specified in the URL) to a different one (specified in the request body)
pub async fn move_note(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
    move_note_request: models::MoveNoteRequest,
) -> Result<serde_json::Value, Error<MoveNoteError>> {
    // 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_body_move_note_request = move_note_request;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes/{noteId}",
        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::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.json(&p_body_move_note_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 `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<MoveNoteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Replace user's master key, reencoding all its contents
pub async fn replace_master_key(
    configuration: &configuration::Configuration,
    replace_master_key_request: models::ReplaceMasterKeyRequest,
) -> Result<serde_json::Value, Error<ReplaceMasterKeyError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_replace_master_key_request = replace_master_key_request;

    let uri_str = format!("{}/api/v1/encryption/master-key", configuration.base_path);
    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.json(&p_body_replace_master_key_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 `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<ReplaceMasterKeyError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Update any detail of an existing note
pub async fn update_note(
    configuration: &configuration::Configuration,
    notebook_id: &str,
    note_id: &str,
    note_request: models::NoteRequest,
) -> Result<models::CreateNote200Response, Error<UpdateNoteError>> {
    // 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_body_note_request = note_request;

    let uri_str = format!(
        "{}/api/v1/{notebookId}/notes/{noteId}",
        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::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_note_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::CreateNote200Response`"))),
            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::CreateNote200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<UpdateNoteError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
