use super::{IInteractionContext, IOutputContext};
use std::cell::RefCell;
use std::fmt;
pub struct InteractionContext<I, O> {
input: I,
output: RefCell<Option<O>>,
}
impl<I, O> InteractionContext<I, O> {
pub fn new(input: I) -> Self {
Self { input, output: RefCell::new(None) }
}
}
impl<I, O> IInteractionContext<I, O> for InteractionContext<I, O> {
fn input(&self) -> &I {
&self.input
}
fn is_handled(&self) -> bool {
self.output.borrow().is_some()
}
fn set_output(&self, output: O) {
let mut slot = self.output.borrow_mut();
if slot.is_some() {
drop(slot);
panic!("InvalidOperationException: Output has already been set.");
}
*slot = Some(output);
}
}
impl<I, O: Clone> IOutputContext<I, O> for InteractionContext<I, O> {
fn get_output(&self) -> O {
match &*self.output.borrow() {
Some(output) => output.clone(),
None => panic!("InvalidOperationException: Output has not been set."),
}
}
}
impl<I: fmt::Debug, O: fmt::Debug> fmt::Debug for InteractionContext<I, O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InteractionContext").field("input", &self.input).field("output", &self.output.borrow()).finish()
}
}