use crate::authentication::Authentication;
use crate::data::MediaItem;
use crate::error::Error;
use crate::Client;
use serde::Serialize;
use std::fs::metadata;
use std::path::Path;

type BoxedError = Box<dyn std::error::Error>;
const STORE_CONTENT_ENDPOINT: &'static str = "apiv2/mediacontentservice/storecontentinvault";

/// Calls `mediacontentservice/storecontentinvault`.
///
/// File name and content type will be set from the path.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
/// * `path` - Path to stored file, for getting name and content type.
/// * `upload_file_id` - The file id to store, returned from `upload_service/upload`.
/// * `vault_id` - The vault to store the content in.
///
/// ## Examples
///
/// ```
/// use std::path::Path;
/// use imagevault::{
///     service::media_content_service,
///     service::upload_service,
///     Client,
///     authentication::ClientCredentialsAuthentication
/// };
///
/// # async fn test() -> Result<(), Box<dyn std::error::Error>> {
/// let authentication = ClientCredentialsAuthentication::default();
/// let client = Client::new(
///     "identity",
///     "secret",
///     "https://myimagevault.local"
///     )?
///     .with_authentication(authentication);
///
/// // Upload a file
/// let file_path = Path::new("my_image.jpg");
/// let upload_file_id = upload_service::upload_from_path(
///     &client,
///     file_path
///     )
///     .await?;
///
/// // Store uploaded content in vault 42
/// let media_item = media_content_service::store_content_in_vault_from_path(
///     &client,
///     file_path,
///     &upload_file_id,
///     42
///     )
///     .await?;
/// # Ok(())
/// # }
/// ```
pub async fn store_content_in_vault_from_path<T: Authentication>(
    client: &Client<T>,
    path: &Path,
    upload_file_id: &str,
    vault_id: u64,
) -> Result<MediaItem, BoxedError> {
    let _md = metadata(path)?;
    let os_file_name = path.file_name().ok_or(std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        "Not a file",
    ))?;
    let file_name = os_file_name.to_str().ok_or(std::io::Error::new(
        std::io::ErrorKind::InvalidData,
        "File name has invalid characters",
    ))?;
    let mime_type = mime_guess::from_path(path)
        .first()
        .ok_or(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Unable to guess mime type for this file, use store_content_in_vault to specify parameters explicitly"))?;
    store_content_in_vault(
        client,
        file_name,
        &mime_type.to_string(),
        upload_file_id,
        vault_id,
    )
    .await
}

/// Calls `mediacontentservice/storecontentinvault`.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
/// * `file_name` - The name of the file.
/// * `content_type` - The content type.
/// * `upload_file_id` - The file id to store, returned from `upload_service/upload`.
/// * `vault_id` - The vault to store the content in.
///
/// ## Examples
///
/// ```
/// use std::path::Path;
/// use imagevault::{
///     service::media_content_service,
///     service::upload_service,
///     Client,
///     authentication::ClientCredentialsAuthentication
/// };
///
/// # async fn test() -> Result<(), Box<dyn std::error::Error>> {
/// let authentication = ClientCredentialsAuthentication::default();
/// let client = Client::new(
///     "identity",
///     "secret",
///     "https://myimagevault.local"
///     )?
///     .with_authentication(authentication);
///
/// // Upload a file
/// let file_path = Path::new("my_image.jpg");
/// let upload_file_id = upload_service::upload_from_path(
///     &client,
///     file_path
///     )
///     .await?;
///
/// // Store uploaded content in vault 42
/// let media_item = media_content_service::store_content_in_vault(
///     &client,
///     "my_image.jpg",
///     "image/jpeg",
///     &upload_file_id,
///     42
///     )
///     .await?;
/// # Ok(())
/// # }
/// ```
pub async fn store_content_in_vault<T: Authentication>(
    client: &Client<T>,
    file_name: &str,
    content_type: &str,
    upload_file_id: &str,
    vault_id: u64,
) -> Result<MediaItem, BoxedError> {
    let full_url = client.base_url.join(STORE_CONTENT_ENDPOINT)?;
    let auth_unwrapped = client
        .authentication
        .as_ref()
        .ok_or_else(|| Error::AuthenticationMissing)?;
    let auth_header = auth_unwrapped
        .lock()
        .unwrap()
        .authenticate(
            &client.client_identity,
            &client.client_secret,
            &client.base_url,
            &client.reqwest_client,
        )
        .await?;
    let data = StoreContentInVaultRequest {
        upload_file_id: upload_file_id.to_string(),
        file_name: file_name.to_string(),
        content_type: content_type.to_string(),
        vault_id,
    };

    let response = client
        .reqwest_client
        .post(full_url)
        .bearer_auth(auth_header)
        .json(&data)
        .send()
        .await?;
    if let Err(err) = response.error_for_status_ref() {
        return Err(Box::new(err));
    } else {
        return Ok(response.json::<MediaItem>().await?);
    }
}

#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct StoreContentInVaultRequest {
    upload_file_id: String,
    #[serde(rename = "filename")]
    file_name: String,
    content_type: String,
    vault_id: u64,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authentication::DummyAuth;
    use crate::testutil;
    #[test]
    fn media_service_store_content_in_vault_test() {
        let mut rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let mock = mockito::mock("POST", mockito::Matcher::Any)
                .expect(1)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(testutil::get_test_data("store_content_in_vault_response"))
                .create();
            let authentication = DummyAuth::new();
            let client = Client::new("client_identity", "client_secret", &mockito::server_url())
                .unwrap()
                .with_authentication(authentication);
            let media_item = store_content_in_vault(
                &client,
                "some_file.jpg",
                "image/jpeg",
                "upload_file_id",
                42,
            )
            .await;
            assert!(media_item.is_ok());
            mock.assert();
        });
    }
    #[test]
    fn media_service_store_content_in_vault_from_path_test() {
        let mut rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let mock = mockito::mock("POST", mockito::Matcher::Any)
                .expect(1)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(testutil::get_test_data("store_content_in_vault_response"))
                .create();
            let authentication = DummyAuth::new();
            let client = Client::new("client_identity", "client_secret", &mockito::server_url())
                .unwrap()
                .with_authentication(authentication);
            let media_item = store_content_in_vault_from_path(
                &client,
                &testutil::get_jpg_test_image_path(),
                "upload_file_id",
                42,
            )
            .await;
            assert!(media_item.is_ok());
            mock.assert();
        });
    }
}
