use std::fmt::Display;
mod diceresult;
mod repeatedrollresult;
mod rollhistory;
mod singlerollresult;
pub use diceresult::*;
pub use repeatedrollresult::*;
pub use rollhistory::*;
pub use singlerollresult::*;
#[derive(Debug, Clone)]
pub enum RollResultType {
Single(SingleRollResult),
Repeated(RepeatedRollResult),
}
#[derive(Debug, Clone)]
pub struct RollResult {
result: RollResultType,
reason: Option<String>,
}
impl RollResult {
pub fn new_single(r: SingleRollResult) -> Self {
RollResult {
result: RollResultType::Single(r),
reason: None,
}
}
pub fn new_repeated(v: Vec<SingleRollResult>, total: Option<i64>) -> Self {
RollResult {
result: RollResultType::Repeated(RepeatedRollResult { rolls: v, total }),
reason: None,
}
}
pub fn add_reason(&mut self, reason: String) {
self.reason = Some(reason);
}
pub fn get_reason(&self) -> Option<&String> {
self.reason.as_ref()
}
pub fn get_result(&self) -> &RollResultType {
&self.result
}
pub fn as_single(&self) -> Option<&SingleRollResult> {
match &self.result {
RollResultType::Single(result) => Some(result),
RollResultType::Repeated(_) => None,
}
}
pub fn as_repeated(&self) -> Option<&RepeatedRollResult> {
match &self.result {
RollResultType::Single(_) => None,
RollResultType::Repeated(results) => Some(results),
}
}
}
impl Display for RollResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.result {
RollResultType::Single(roll_result) => {
write!(f, "{}", roll_result.to_string(true))?;
if let Some(reason) = &self.reason {
write!(f, ", Reason: `{}`", reason)?;
}
}
RollResultType::Repeated(repeated_result) => match repeated_result.get_total() {
Some(total) => {
(*repeated_result)
.iter()
.try_for_each(|res| writeln!(f, "`{}`", res.to_string_history()))?;
write!(f, "Sum: **{}**", total)?;
if let Some(reason) = &self.reason {
write!(f, ", Reason: `{}`", reason)?;
}
}
None => {
(*repeated_result)
.iter()
.try_for_each(|res| writeln!(f, "{}", res.to_string(true)))?;
if let Some(reason) = &self.reason {
write!(f, "Reason: `{}`", reason)?;
}
}
},
}
Ok(())
}
}
impl Display for SingleRollResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_string(true))?;
Ok(())
}
}