use crate::authentication::Authentication;
use crate::data::MediaItem;
use crate::error::Error;
use crate::Client;
use serde::Serialize;

type BoxedError = Box<dyn std::error::Error>;
const SAVE_ENDPOINT: &'static str = "/apiv2/mediaservice/save";
/// Calls `mediaservice/save`.
///
/// Returns an `AuthenticationMissing` error
/// if the `Client` does not have any `Authentication` set.
///
/// ## Arguments
/// * `client` - The ImageVault `Client` to use.
/// * `media_items` - A list of `MediaItems` to save.
/// * `save_options` - A `MediaServiceSaveOption` describing what to save.
///
/// ## Examples
///
/// ```
/// use std::path::Path;
/// use imagevault::{
///     service::media_content_service,
///     service::upload_service,
///     service::media_service,
///     service::media_service::MediaServiceSaveOptions,
///     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?;
///
/// // Mark the newly uploaded content as organized
/// let save_result = media_service::save(
///     &client,
///     vec![&media_item],
///     MediaServiceSaveOptions::MarkAsOrganized
///     )
///     .await?;
/// # Ok(())
/// # }
/// ```
pub async fn save<T: Authentication>(
    client: &Client<T>,
    media_items: Vec<&MediaItem>,
    save_options: MediaServiceSaveOptions,
) -> Result<(), BoxedError> {
    let full_url = client.base_url.join(SAVE_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 = SaveRequest {
        media_items: media_items
            .iter()
            .map(|m| MediaItemId { id: m.id })
            .collect(),
        save_options,
    };

    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(());
    }
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SaveRequest {
    media_items: Vec<MediaItemId>,
    save_options: MediaServiceSaveOptions,
}

#[derive(Serialize)]
struct MediaItemId {
    #[serde(rename = "Id")]
    id: u64,
}

#[derive(Serialize)]
pub enum MediaServiceSaveOptions {
    Default = 0,
    Metadata = 1,
    Categories = 2,
    MarkAsOrganized = 4,
    Vault = 8,
    Agreements = 16,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::authentication::DummyAuth;
    use crate::data::MediaItem;
    use chrono::{offset::TimeZone, FixedOffset};
    #[test]
    fn media_service_save_mark_as_organized_test() {
        let mut rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let mock = mockito::mock("POST", SAVE_ENDPOINT)
                .expect(1)
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body("")
                .create();
            let authentication = DummyAuth::new();
            let client = Client::new("client_identity", "client_secret", &mockito::server_url())
                .unwrap()
                .with_authentication(authentication);
            let media_item = MediaItem {
                id: 42,
                name: "Test".into(),
                vault_id: 42,
                added_by: "Test".into(),
                date_added: FixedOffset::east(2 * 3600)
                    .ymd(2000, 01, 01)
                    .and_hms(0, 0, 0),
            };

            let save_result = save(
                &client,
                vec![&media_item],
                MediaServiceSaveOptions::MarkAsOrganized,
            )
            .await;
            assert!(save_result.is_ok());
            mock.assert();
        });
    }
}
