use std::collections::HashMap;
use std::sync::Arc;
use once_cell::sync::Lazy;
use tauri::Webview;
mod command;
use command::{Cmd, CommandError};
pub use command::{StoreState, ApplicationState, ActionCallback};
pub const INIT_FUNC: &str = "initialize";
pub fn command_handler<T: ApplicationState + 'static>(
webview: &mut Webview,
arg: &str,
state: &'static Lazy<Arc<dyn StoreState<T>>>,
commands: &'static Lazy<HashMap<String, Box<dyn Fn(T, serde_json::Value) -> tauri::Result<T> + Send + Sync + 'static>>>,
) -> Result<(), String> {
match serde_json::from_str(arg) {
Err(err) => {
println!("{}", err);
Err(err.to_string())
},
Ok(command) => {
match command {
Cmd::InitializeStore { callback, error } => tauri::execute_promise(webview, move || {
println!("locking init state");
let mut state_data = state.get_data()?;
println!("init state lock");
match commands.get(INIT_FUNC) {
Some(ref func) => {
match func((*state_data).clone(), serde_json::Value::Null) {
Ok(s) => {
*state_data = s;
println!("Init state: {}", *state_data);
Ok((*state_data).clone())
},
Err(err) => Err(err)
}
},
_ => Ok((*state_data).clone())
}
}, callback, error),
Cmd::Action { action, data, callback, error } => tauri::execute_promise(webview, move || {
match commands.get(&action) {
Some(ref func) => {
let mut state_data = state.get_data()?;
match func((*state_data).clone(), data) {
Ok(s) => {
*state_data = s;
println!("New state: {}", *state_data);
Ok((*state_data).clone())
},
Err(err) => Err(err)
}
},
_ => {
println!("Unknown action: {}", action);
Err(CommandError::new(format!("Unknown action: {}", action)).into())
}
}
}, callback, error)
}
Ok(())
}
}
}
pub fn update_state<T: ApplicationState>(webview: &mut tauri::WebviewMut, state: T) -> tauri::Result<()> {
tauri::event::emit(webview, String::from("state-update"), Some(state))
}