use crate::error::ServiceError;
use crate::model::dto::ApplicationSettingDto;
use crate::model::entity::ApplicationSetting;
use diesel_async::AsyncPgConnection;
use reqwest::StatusCode;
type Rgb = (u8, u8, u8);
pub type HeatmapColors = (Rgb, Rgb, Rgb, Rgb);
pub async fn find_by_key(
key: &str,
conn: &mut AsyncPgConnection,
) -> Result<ApplicationSettingDto, ServiceError> {
let result = ApplicationSetting::find_by_key(key, conn).await?;
Ok(result)
}
pub fn hex_to_rgb(hex: &str) -> Result<(u8, u8, u8), ServiceError> {
let error_msg = "Invalid heatmap color hex code";
if hex.len() != 6 {
return Err(ServiceError::new(
StatusCode::INTERNAL_SERVER_ERROR,
error_msg,
));
}
let red_slice = hex.get(0..2);
let red = match red_slice {
Some(red) => u8::from_str_radix(red, 16)
.map_err(|_| ServiceError::new(StatusCode::INTERNAL_SERVER_ERROR, error_msg))?,
None => {
return Err(ServiceError::new(
StatusCode::INTERNAL_SERVER_ERROR,
error_msg,
));
}
};
let green_slice = hex.get(2..4);
let green = match green_slice {
Some(green) => u8::from_str_radix(green, 16)
.map_err(|_| ServiceError::new(StatusCode::INTERNAL_SERVER_ERROR, error_msg))?,
None => {
return Err(ServiceError::new(
StatusCode::INTERNAL_SERVER_ERROR,
error_msg,
));
}
};
let blue_slice = hex.get(4..6);
let blue = match blue_slice {
Some(blue) => u8::from_str_radix(blue, 16)
.map_err(|_| ServiceError::new(StatusCode::INTERNAL_SERVER_ERROR, error_msg))?,
None => {
return Err(ServiceError::new(
StatusCode::INTERNAL_SERVER_ERROR,
error_msg,
));
}
};
Ok((red, green, blue))
}
pub async fn get_heatmap_colors(
conn: &mut AsyncPgConnection,
) -> Result<HeatmapColors, ServiceError> {
let red_hex = find_by_key("heatmap_red", conn).await?;
let orange_hex = find_by_key("heatmap_orange", conn).await?;
let green_hex = find_by_key("heatmap_green", conn).await?;
let black_hex = find_by_key("heatmap_black", conn).await?;
let red = hex_to_rgb(&red_hex.value).map_err(ServiceError::from)?;
let orange = hex_to_rgb(&orange_hex.value).map_err(ServiceError::from)?;
let green = hex_to_rgb(&green_hex.value).map_err(ServiceError::from)?;
let black = hex_to_rgb(&black_hex.value).map_err(ServiceError::from)?;
Ok((red, orange, green, black))
}