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
use hashbrown::HashMap;
use log::info;
use serde_json::Value;
use specs::{Entity, ReadExpect, ReadStorage, System, WriteExpect};

use crate::{
    encode_message, ChunkRequestsComp, ClientFilter, Clients, EncodedMessage, Event, EventProtocol,
    Events, Message, MessageType, Transports, Vec2,
};

pub struct EventsBroadcastSystem;

impl<'a> System<'a> for EventsBroadcastSystem {
    type SystemData = (
        ReadExpect<'a, Transports>,
        ReadExpect<'a, Clients>,
        WriteExpect<'a, Events>,
        ReadStorage<'a, ChunkRequestsComp>,
    );

    fn run(&mut self, data: Self::SystemData) {
        let (transports, clients, mut events, requests) = data;

        if events.queue.is_empty() {
            return;
        }

        let is_interested = |coords: &Vec2<i32>, entity: Entity| {
            if let Some(request) = requests.get(entity) {
                return request.is_interested(coords);
            }

            return false;
        };

        let serialize_payload = |name: String, payload: Option<Value>| EventProtocol {
            name,
            payload: if payload.is_none() {
                String::from("{}")
            } else {
                payload.unwrap().to_string()
            },
        };

        // ID to a set of events, serialized.
        let mut dispatch_map: HashMap<String, Vec<EventProtocol>> = HashMap::new();
        let mut transports_map: Vec<EventProtocol> = vec![];

        events.queue.drain(..).for_each(|event| {
            let Event {
                name,
                payload,
                filter,
                location,
            } = event;

            let serialized = serialize_payload(name, payload);

            if !transports.is_empty() {
                transports_map.push(serialized.to_owned());
            }

            // Checks if location is required, otherwise just sends.
            let mut send_to_id = |id: &str| {
                if let Some(client) = clients.get(id) {
                    let mut queue = dispatch_map.remove(id).unwrap_or_default();
                    if let Some(location) = &location {
                        if is_interested(location, client.entity.to_owned()) {
                            queue.push(serialized.to_owned());
                        }
                    } else {
                        queue.push(serialized.to_owned());
                    }
                    dispatch_map.insert(id.to_owned(), queue);
                }
            };

            if let Some(filter) = filter {
                if let ClientFilter::Direct(id) = &filter {
                    send_to_id(id);
                    return;
                }

                for (id, _) in clients.iter() {
                    match &filter {
                        ClientFilter::All => {}
                        ClientFilter::Include(ids) => {
                            if !ids.iter().any(|i| *i == *id) {
                                continue;
                            }
                        }
                        ClientFilter::Exclude(ids) => {
                            if ids.iter().any(|i| *i == *id) {
                                continue;
                            }
                        }
                        _ => {}
                    };

                    send_to_id(id);
                }
            }
            // No filter, but a location is set.
            else if let Some(location) = &location {
                for (id, client) in clients.iter() {
                    if let Some(request) = requests.get(client.entity.to_owned()) {
                        if request.is_interested(location) {
                            let mut queue = dispatch_map.remove(id).unwrap_or_default();
                            queue.push(serialized.clone());
                            dispatch_map.insert(id.to_owned(), queue);
                        }
                    }
                }
            } else {
                clients.iter().for_each(|(id, _)| {
                    let mut queue = dispatch_map.remove(id).unwrap_or_default();
                    queue.push(serialized.clone());
                    dispatch_map.insert(id.to_owned(), queue);
                });
            }
        });

        // Process the dispatch map, sending them directly for fastest event responses.
        dispatch_map.into_iter().for_each(|(id, events)| {
            if events.is_empty() {
                return;
            }

            let client = clients.get(&id);

            if client.is_none() {
                return;
            }

            let client = client.unwrap();
            let message = Message::new(&MessageType::Event).events(&events).build();
            let encoded = EncodedMessage(encode_message(&message));

            client.addr.do_send(encoded);
        });

        if !transports.is_empty() {
            let message = Message::new(&MessageType::Event)
                .events(&transports_map)
                .build();
            let encoded = EncodedMessage(encode_message(&message));
            transports.values().for_each(|r| r.do_send(encoded.clone()));
        }
    }
}