use std::error::Error;
use log::error;
use reqwest::StatusCode;
use serde::{Serialize, Deserialize};
use starkingdoms_protocol::api::APISavedPlayerData;
#[derive(Serialize, Deserialize)]
pub struct BeaminRequest {
pub api_token: String,
pub user_auth_realm_id: String,
pub user_auth_token: String
}
#[derive(Serialize, Deserialize)]
pub struct BeaminResponse {
pub save_id: String,
pub save: APISavedPlayerData
}
pub async fn load_player_data_from_api(token: &str, user_id: &str, internal_token: &str) -> Result<APISavedPlayerData, Box<dyn Error>> {
let client = reqwest::Client::new();
let req_body = BeaminRequest {
api_token: internal_token.to_owned(),
user_auth_realm_id: user_id.to_owned(),
user_auth_token: token.to_owned()
};
let res = client.post(format!("{}/beamin", std::env::var("STK_API_URL").unwrap())).header("Content-Type", "application/json").body(serde_json::to_string(&req_body)?).send().await?;
if res.status() == StatusCode::NO_CONTENT {
return Ok(APISavedPlayerData::default())
}
if res.status() != StatusCode::OK {
error!("error with API call (status: {}, body: {})", res.status(), res.text().await?);
return Err("Error with API call".into())
}
let resp: BeaminResponse = serde_json::from_str(&res.text().await?)?;
Ok(resp.save)
}
#[derive(Serialize, Deserialize)]
pub struct BeamoutRequest {
pub api_token: String,
pub user_auth_realm_id: String,
pub user_auth_token: String,
pub data: APISavedPlayerData
}
pub async fn save_player_data_to_api(data: &APISavedPlayerData, token: &str, user_id: &str, internal_token: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
let client = reqwest::Client::new();
let req_body = BeamoutRequest {
api_token: internal_token.to_owned(),
user_auth_realm_id: user_id.to_owned(),
user_auth_token: token.to_owned(),
data: data.to_owned()
};
let res = client.post(format!("{}/beamout", std::env::var("STK_API_URL").unwrap())).header("Content-Type", "application/json").body(serde_json::to_string(&req_body)?).send().await?;
if res.status() != StatusCode::OK {
error!("error with API call (status: {}, body: {})", res.status(), res.text().await?);
return Err("Error with API call".into())
}
Ok(())
}