1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::fmt::Debug;
use std::hash::Hash;
use serde::{ Serialize };
use serde::de::DeserializeOwned;

use crate::v2::driver::dom::{ log, error, AppEvent };

/// The Machine trait.
/// Implement it on your structur to automatically implement Sender and Reveiver.
/// This trait handles the logic of Finite State Machine and provide some
/// trait binding on the internal type to allow some optimisations.
pub trait Machine: Sized + 'static {
    type Events: Debug + Clone + PartialEq + Serialize + Eq + Hash + Serialize + DeserializeOwned;
    type State: Send + Debug + Clone + PartialEq + Serialize + Eq + Hash + Serialize + DeserializeOwned;
    type States: Debug + Clone + PartialEq + Serialize + Eq + Hash + Serialize + DeserializeOwned;
    type Failures: Debug + Clone + PartialEq + Serialize + Eq + Hash + Serialize + DeserializeOwned;

    fn new() -> Self;

    /// transition gets an event and change the internal data relative to the type of event
    /// and the returns the state of the machine
    fn transition(&mut self, event: Self::Events) -> Result<&Self::States, Self::Failures>;

    /// run computes the state of the machine relative to its state
    fn run(&mut self) -> Result<&Self::States, Self::Failures>;

    /// return the state wrapped in its enum variant
    fn get_state(&self) -> &Self::States;
    /// return the state wrapped in its enum variant mutably
    fn get_state_mut(&mut self) -> &mut Self::States;
    /// return a reference the raw state with the values
    fn get_raw_state(&self) -> &Self::State;
    //// return a mutable reference to the raw state with the values
    fn get_raw_state_mut(&mut self) -> &mut Self::State;

    fn get_data(&mut self) -> mustache::MapBuilder {
       mustache::MapBuilder::new().insert("state", self.get_raw_state()).unwrap()
    }

    // fn get_childrens(&mut self) -> mustache::MapBuilder;
    fn get_childrens(&mut self) -> mustache::MapBuilder {
      let data = self.get_data().build();
      let data = mustache::MapBuilder::new().insert_fn("pre_render", move |text| {
          let tpl = mustache::compile_str(&text).expect("could not compile template");
          // log(format!("render text: {}", text).as_str());
          tpl.render_data_to_string(&data).expect("could not render template")
      });
      data
   }

    /// This trait handles the communication of the machine with the external world.
    /// Inside of an App, this method is used to receive a given message and
    /// then fires the transition and run function.
    /// It handles serialization and deserialization of events based on Internal type.
    fn receive(&mut self, evt: AppEvent) -> Result<(), String> where AppEvent: DeserializeOwned {
      let tpl = mustache::compile_str(&evt.event).map_err(|e| {
           error(format!("could not compile template for event: {:?}", e).as_str());
           e
       }).unwrap();
       let data = self.get_data();
       let evt = tpl.render_data_to_string(&data.build()).map_err(|e| {
           error(format!("could not render data for event: {:?}", e).as_str());
           e
       }).unwrap();
       let evt: Result<Self::Events, serde_json::error::Error> = serde_json::from_str(&evt);
       match evt {
           Ok(evt) => { 
               match self.transition(evt.clone()) {
                  Ok(_s) => Ok(()),
                  Err(e) => Err(format!("failed transition: {:?}", e)),
               }
           }
           Err(ref e) => {
               // error(format!("{} {:?}", "could not parse Events: ", evt).as_str());
               // error(format!("{:?}", e).as_str());
               Err(format!("{} {:?}", "could not parse Events: ", evt))
           }
       }
   }
}