use fmt::Debug;
use crate::{Context, Vector};
use std::{error::Error, fmt};
pub type Action = fn(Context) -> Result<ActionResult, ActionError>;
#[derive(Debug)]
pub enum ActionResult {
Done,
ShowHelpRequest(Context),
ShowOtherHelpReq(Context, usize, Vector<String>),
Result(Context, Action),
Custom(Box<dyn CustomResult>),
}
pub trait CustomResult {
fn debug_message(&self) -> &str;
}
impl Debug for dyn CustomResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.debug_message())
}
}
#[derive(Debug)]
pub struct ActionError {
pub value: String,
pub kind: ActionErrorKind,
pub context: Context,
pub related_error: Option<Box<dyn Error>>,
pub printed: bool,
}
#[derive(Debug)]
pub enum ActionErrorKind {
Custom,
NoActionRegistered,
None,
}
impl ActionError {
pub fn new<T: Into<String>>(
value: T,
kind: ActionErrorKind,
context: Context,
related_error: Option<Box<dyn Error>>,
) -> Self {
Self {
value: value.into(),
kind,
context,
related_error,
printed: false,
}
}
pub fn without_related_error(value: String, kind: ActionErrorKind, context: Context) -> Self {
Self {
value,
kind,
context,
related_error: None,
printed: false,
}
}
}
impl fmt::Display for ActionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
ActionErrorKind::Custom => write!(f, "{}", self.value),
ActionErrorKind::NoActionRegistered => {
write!(f, "{} does not have its own action.", self.value)
}
ActionErrorKind::None => write!(f, "no action error"),
}
}
}
impl Error for ActionError {}