use std::collections::HashMap;
use std::error::Error;
use std::fmt::{Debug, Display};
use std::{fmt, io};
use serde::export::Formatter;
use serde_json::Value;
use crate::communication::{MethodCall, MethodResult};
use std::any::Any;
pub type Result<T> = std::result::Result<T, MethodError>;
pub struct MethodError {
display: String,
debug: String,
}
impl MethodError {
pub fn message(message: impl ToString) -> Self {
Self {
display: message.to_string(),
debug: message.to_string(),
}
}
}
impl From<io::Error> for MethodError {
fn from(error: io::Error) -> Self {
Self {
display: format!("{}", &error),
debug: format!("{:?}", &error),
}
}
}
impl From<Box<dyn Any + Send + 'static>> for MethodError {
fn from(error: Box<dyn Any + Send + 'static>) -> Self {
Self {
display: format!("{:?}", &error),
debug: format!("{:?}", &error),
}
}
}
impl From<serde_json::Error> for MethodError {
fn from(error: serde_json::Error) -> Self {
Self {
display: format!("{}", &error),
debug: format!("{:?}", &error),
}
}
}
impl Error for MethodError {}
impl Display for MethodError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(self.display.as_str())
}
}
impl Debug for MethodError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(self.debug.as_str())
}
}
pub trait Method {
fn name(&self) -> String;
fn description(&self) -> String;
fn help(&self) -> String;
fn set_arguments(&mut self, arguments: HashMap<String, Value>) -> Result<()>;
}
pub trait MethodCallable: Method {
fn call(&mut self, context: MethodCall) -> MethodResult;
}