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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use async_trait::async_trait;
use downcast_rs::{impl_downcast, Downcast};

use serde::Serialize;
use serde_json::Value;
use std::{any::Any, collections::VecDeque, fmt::Debug};

use chrono::{DateTime, Utc};

use uuid::Uuid;

pub trait Message: Sync + Send + Any + Downcast {
	fn externally_notifiable(&self) -> bool {
		false
	}
	fn internally_notifiable(&self) -> bool {
		false
	}

	fn metadata(&self) -> MessageMetadata;
	fn outbox(&self) -> Box<dyn OutBox>;
	// {
	//     let metadata = self.metadata();
	//     Outbox::new(metadata.aggregate_id, metadata.topic, self.state())
	// }
	fn message_clone(&self) -> Box<dyn Message>;

	fn state(&self) -> String;

	fn to_message(self) -> Box<dyn Message + 'static>;
}

impl_downcast!(Message);
impl Debug for dyn Message {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}", self.metadata().topic)
	}
}

pub struct MessageMetadata {
	pub aggregate_id: String,
	pub topic: String,
}

// Trait To Mark Event As Mail Sendable. Note that template_name must be specified.
pub trait MailSendable: Message + Serialize + Send + Sync + 'static {
	fn template_name(&self) -> String;
	fn to_json(&self) -> Value {
		serde_json::to_value(self).unwrap()
	}
}

#[macro_export]
macro_rules! MailSendableMacro {
    (

        $( #[$attr:meta] )*
        $pub:vis
        struct $mail_sendable:ident {
            $(
                $(#[$field_attr:meta])*
                $field_vis:vis // this visibility will be applied to the getters instead
                $field_name:ident : $field_type:ty
            ),* $(,)?
    }
    ) => {
        $( #[$attr])*
        impl $crate::lib_components::MailSendable for $mail_sendable {
            fn template_name(&self) -> String {
                // * subject to change
                stringify!($mail_sendable).into()
            }
        }
    };
}

pub trait Command: 'static + Send + Any + Sync {}

pub trait Aggregate: Send + Sync + Default {
	fn collect_events(&mut self) -> VecDeque<Box<dyn Message>> {
		if !self.events().is_empty() {
			self.take_events()
		} else {
			VecDeque::new()
		}
	}
	fn events(&self) -> &std::collections::VecDeque<Box<dyn Message>>;

	fn take_events(&mut self) -> std::collections::VecDeque<Box<dyn Message>>;
	fn raise_event(&mut self, event: Box<dyn Message>);
}

#[macro_export]
macro_rules! count {
    () => (0usize);
    ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));
}

#[macro_export]
macro_rules! AggregateMacro {
    (

        $( #[$attr:meta] )*
        $pub:vis
        struct $aggregate:ident {
            $(#[$event_field_attr:meta])*
            events: std::collections::VecDeque<std::boxed::Box<dyn Message>>,
            $(
                $(#[$field_attr:meta])*
                $field_vis:vis // this visibility will be applied to the getters instead
                $field_name:ident : $field_type:ty
            ),* $(,)?

        }
    ) => {

        $( #[$attr])*
        impl $crate::prelude::Aggregate for $aggregate {
            fn events(&self) -> &std::collections::VecDeque<Box<dyn Message>> {
                &self.events
            }
            fn take_events(&mut self) -> std::collections::VecDeque<Box<dyn Message>> {
                std::mem::take(&mut self.events)
            }
            fn raise_event(&mut self, event: Box<dyn Message>) {
                self.events.push_back(event)
            }
        }

    };
}

#[macro_export]
macro_rules! Entity {
    (

        $( #[$attr:meta] )*
        $pub:vis
        struct $classic:ident {
            $(
                $(#[$field_attr:meta])*
                $field_vis:vis // this visibility will be applied to the getters instead
                $field_name:ident : $field_type:ty
            ),* $(,)?
    }
) => {
        impl $classic {
            $(
                $crate::paste!{
                pub fn [< set_ $field_name >] (mut self, $field_name:$field_type)-> Self{
                    self.$field_name = $field_name;
                    self

                }
            }
            )*

        }
    };
}

#[async_trait]
pub trait OutBox: Send + Sync + 'static {
	fn convert_event(&self) -> Box<dyn Message>;
	fn tag_processed(&mut self);

	fn id(&self) -> Uuid;
	fn aggregate_id(&self) -> &str;
	fn topic(&self) -> &str;
	fn state(&self) -> &str;
	fn processed(&self) -> bool;
	fn create_dt(&self) -> DateTime<Utc>;
}

#[macro_export]
macro_rules! convert_event {
    ( $obj:expr, $( $type: ty ), * ) => {
        match $obj.topic.as_str() {
          $(stringify!($type)=> serde_json::from_str::<$type>($obj.state.as_str()).expect("Given type not deserializable!").message_clone() ,)*
          _ => {
                panic!("Such event not allowed to process through outbox.");
          }
        }
    };
}