2020-11-04 20:09:39 +00:00
|
|
|
use crate::context::Context;
|
2021-05-15 23:45:26 +00:00
|
|
|
use crate::db::sqlite::Variables;
|
2020-11-04 20:09:39 +00:00
|
|
|
use crate::db::variables::UserAndRoom;
|
|
|
|
use crate::error::BotError;
|
|
|
|
use crate::error::DiceRollingError;
|
|
|
|
use crate::parser::Amount;
|
|
|
|
use crate::parser::Element as NewElement;
|
|
|
|
use futures::stream::{self, StreamExt, TryStreamExt};
|
2021-05-13 20:24:17 +00:00
|
|
|
use std::slice;
|
|
|
|
|
|
|
|
/// Calculate the amount of dice to roll by consulting the database
|
|
|
|
/// and replacing variables with corresponding the amount. Errors out
|
|
|
|
/// if it cannot find a variable defined, or if the database errors.
|
|
|
|
pub async fn calculate_single_die_amount(
|
|
|
|
amount: &Amount,
|
|
|
|
ctx: &Context<'_>,
|
|
|
|
) -> Result<i32, BotError> {
|
|
|
|
calculate_dice_amount(slice::from_ref(amount), ctx).await
|
|
|
|
}
|
2020-04-20 17:19:50 +00:00
|
|
|
|
2021-02-02 22:02:43 +00:00
|
|
|
/// Calculate the amount of dice to roll by consulting the database
|
|
|
|
/// and replacing variables with corresponding amounts. Errors out if
|
|
|
|
/// it cannot find a variable defined, or if the database errors.
|
2020-11-04 20:09:39 +00:00
|
|
|
pub async fn calculate_dice_amount(amounts: &[Amount], ctx: &Context<'_>) -> Result<i32, BotError> {
|
|
|
|
let stream = stream::iter(amounts);
|
2021-05-15 23:45:26 +00:00
|
|
|
let variables = &ctx
|
|
|
|
.db
|
|
|
|
.get_user_variables(&ctx.username, ctx.room_id().as_str())
|
|
|
|
.await?;
|
2020-11-04 20:09:39 +00:00
|
|
|
|
|
|
|
use DiceRollingError::VariableNotFound;
|
2021-02-02 22:02:43 +00:00
|
|
|
let dice_amount: i32 = stream
|
2020-11-04 20:09:39 +00:00
|
|
|
.then(|amount| async move {
|
|
|
|
match &amount.element {
|
2021-02-02 22:02:43 +00:00
|
|
|
NewElement::Number(num_dice) => Ok(num_dice * amount.operator.mult()),
|
2020-11-04 20:09:39 +00:00
|
|
|
NewElement::Variable(variable) => variables
|
|
|
|
.get(variable)
|
2021-02-02 22:02:43 +00:00
|
|
|
.ok_or_else(|| VariableNotFound(variable.clone()))
|
|
|
|
.map(|i| *i),
|
2020-11-04 20:09:39 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
.try_fold(0, |total, num_dice| async move { Ok(total + num_dice) })
|
2021-02-02 22:02:43 +00:00
|
|
|
.await?;
|
2020-11-04 20:09:39 +00:00
|
|
|
|
2021-02-02 22:02:43 +00:00
|
|
|
Ok(dice_amount)
|
2020-11-04 20:09:39 +00:00
|
|
|
}
|