use crate::Router;
#[derive(Clone, Debug, Default)]
pub enum ActionContext<State> {
#[default]
Unit,
System(SystemContext<State>),
}
impl<State> From<SystemContext<State>> for ActionContext<State> {
fn from(context: SystemContext<State>) -> Self {
Self::System(context)
}
}
#[derive(Clone, Debug, Default)]
pub struct SystemContext<State> {
pub router: Router<State>,
}
impl<State> From<Router<State>> for SystemContext<State> {
fn from(router: Router<State>) -> Self {
Self { router }
}
}
#[derive(Debug, thiserror::Error)]
#[error("Attempted to access state when it was not ready.")]
pub struct StateNotReadyError;
#[derive(Clone, Debug, Default)]
pub struct Context<State> {
pub action: ActionContext<State>,
pub state: Option<State>,
}
impl<State> Context<State> {
pub fn from_action(action: ActionContext<State>) -> Self {
Self {
action,
state: None,
}
}
pub fn from_state(state: State) -> Self {
Self {
action: ActionContext::Unit,
state: Some(state),
}
}
pub fn state(&self) -> Result<State, StateNotReadyError>
where
State: Clone,
{
match self.state.clone() {
Some(state) => Ok(state),
None => Err(StateNotReadyError),
}
}
pub fn with_action(action: ActionContext<State>, state: State) -> Self {
Self {
action,
state: Some(state),
}
}
}
impl<State> From<ActionContext<State>> for Context<State> {
fn from(action: ActionContext<State>) -> Self {
Self::from_action(action)
}
}
impl<State> From<State> for Context<State> {
fn from(state: State) -> Self {
Self::from_state(state)
}
}