use std::sync::Arc;
use crate::error::{Error, Result};
use crate::value::{CommandDataKind, Value};
use crate::dev::CommandInfo;
use super::dev::{some_doc, Access, Dev, ModelRef};
use super::def::{CommandDef, ExecFn};
use super::Model;
pub struct Command<M: Model> {
def: Arc<CommandDef<M>>,
}
impl<M: Model> Command<M> {
pub(super) fn new(def: Arc<CommandDef<M>>) -> Self {
Self { def }
}
#[inline]
pub fn name(&self) -> &str {
&self.def.name
}
pub(super) fn access(&self) -> Access {
match &self.def.exec {
Some(ExecFn::ExclusiveSync(_) | ExecFn::ExclusiveAsync(_)) => Access::Exclusive,
_ => Access::Shared,
}
}
pub(super) fn may_block(&self) -> bool {
matches!(&self.def.exec, Some(ExecFn::SharedSync(_) | ExecFn::ExclusiveSync(_)))
}
pub fn info(&self) -> CommandInfo {
CommandInfo {
display_level: self.def.display_level,
in_kind: self.def.in_kind.unwrap_or(CommandDataKind::Void),
out_kind: self.def.out_kind.unwrap_or(CommandDataKind::Void),
in_doc: some_doc(&self.def.in_doc),
out_doc: some_doc(&self.def.out_doc),
}
}
pub(super) async fn exec(&self, dev: &Dev<M>, model: &mut ModelRef<'_, M>, input: Value) -> Result<Value> {
match &self.def.exec {
Some(ExecFn::SharedSync(func)) => func(model.shared(), dev, input),
Some(ExecFn::ExclusiveSync(func)) => func(model.exclusive()?, dev, input),
Some(ExecFn::SharedAsync(func)) => func(model.shared(), dev, input).await,
Some(ExecFn::ExclusiveAsync(func)) => func(model.exclusive()?, dev, input).await,
None => Err(Error::not_implemented()
.with_description(format!("The command {} of the device {} has no execution function", self.name(), dev.name()))),
}
}
}