use crate::extractors::client_auth::APIClientAuth;
use crate::server::HttpResult;
use actix_web::{web, HttpResponse};
use ruma::api::client::media;
use ruma::{OwnedServerName, UInt};

#[derive(serde::Deserialize)]
pub struct MediaInfoInPath {
    server_name: OwnedServerName,
    media_id: String,
}

/// Download a media
pub async fn download(auth: APIClientAuth, path: web::Path<MediaInfoInPath>) -> HttpResult {
    let res = auth
        .send_request(media::get_content::v3::Request::new(
            path.media_id.clone(),
            path.server_name.clone(),
        ))
        .await?;

    let mut http_res = HttpResponse::Ok();
    if let Some(content_type) = res.content_type {
        http_res.content_type(content_type);
    }

    Ok(http_res.body(res.file))
}

#[derive(serde::Deserialize)]
pub struct MediaThumbnailQuery {
    width: Option<UInt>,
    height: Option<UInt>,
}

/// Get a media thumbnail
pub async fn thumbnail(
    auth: APIClientAuth,
    path: web::Path<MediaInfoInPath>,
    query: web::Query<MediaThumbnailQuery>,
) -> HttpResult {
    let res = auth
        .send_request(media::get_content_thumbnail::v3::Request::new(
            path.media_id.clone(),
            path.server_name.clone(),
            query.width.unwrap_or(UInt::new(500).unwrap()),
            query.height.unwrap_or(UInt::new(500).unwrap()),
        ))
        .await?;

    let mut http_res = HttpResponse::Ok();
    if let Some(content_type) = res.content_type {
        http_res.content_type(content_type);
    }

    Ok(http_res.body(res.file))
}