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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::collections::{HashMap, HashSet};

use bevy_app::{App, Plugin, PreUpdate};
use bevy_ecs::entity::Entity;
use bevy_ecs::prelude::{
    Added, Changed, Commands, DetectChanges, Event, EventReader, EventWriter, IntoSystemConfigs,
    Mut, Or, Query, Res,
};
use petgraph::graph::NodeIndex;
use petgraph::prelude::EdgeRef;
use petgraph::{Direction, Graph};
use tracing::{debug, info, trace, warn};
use valence_server::client::{Client, SpawnClientsSet};
use valence_server::event_loop::PacketEvent;
use valence_server::protocol::packets::play::command_tree_s2c::NodeData;
use valence_server::protocol::packets::play::{CommandExecutionC2s, CommandTreeS2c};
use valence_server::protocol::WritePacket;
use valence_server::EventLoopPreUpdate;

use crate::graph::{CommandEdgeType, CommandGraph, CommandNode};
use crate::parsers::ParseInput;
use crate::scopes::{CommandScopePlugin, CommandScopes};
use crate::{CommandRegistry, CommandScopeRegistry, CommandSystemSet, ModifierValue};

pub struct CommandPlugin;

impl Plugin for CommandPlugin {
    fn build(&self, app: &mut App) {
        app.add_plugins(CommandScopePlugin)
            .add_event::<CommandExecutionEvent>()
            .add_event::<CommandProcessedEvent>()
            .add_systems(PreUpdate, insert_scope_component.after(SpawnClientsSet))
            .add_systems(
                EventLoopPreUpdate,
                (
                    update_command_tree,
                    command_tree_update_with_client,
                    read_incoming_packets.before(CommandSystemSet),
                    parse_incoming_commands.in_set(CommandSystemSet),
                ),
            );

        let graph: CommandGraph = CommandGraph::new();
        let modifiers = HashMap::new();
        let parsers = HashMap::new();
        let executables = HashSet::new();

        app.insert_resource(CommandRegistry {
            graph,
            parsers,
            modifiers,
            executables,
        });
    }
}

/// This event is sent when a command is sent (you can send this with any
/// entity)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Event)]
pub struct CommandExecutionEvent {
    /// the command that was executed eg. "teleport @p 0 ~ 0"
    pub command: String,
    /// usually the Client entity but it could be a command block or something
    /// (whatever the library user wants)
    pub executor: Entity,
}

/// This will only be sent if the command was successfully parsed and an
/// executable was found
#[derive(Debug, Clone, PartialEq, Eq, Event)]
pub struct CommandProcessedEvent {
    /// the command that was executed eg. "teleport @p 0 ~ 0"
    pub command: String,
    /// usually the Client entity but it could be a command block or something
    /// (whatever the library user wants)
    pub executor: Entity,
    /// the modifiers that were applied to the command
    pub modifiers: HashMap<ModifierValue, ModifierValue>,
    /// the node that was executed
    pub node: NodeIndex,
}

fn insert_scope_component(mut clients: Query<Entity, Added<Client>>, mut commands: Commands) {
    for client in &mut clients {
        commands.entity(client).insert(CommandScopes::new());
    }
}

fn read_incoming_packets(
    mut packets: EventReader<PacketEvent>,
    mut event_writer: EventWriter<CommandExecutionEvent>,
) {
    for packet in packets.read() {
        let client = packet.client;
        if let Some(packet) = packet.decode::<CommandExecutionC2s>() {
            event_writer.send(CommandExecutionEvent {
                command: packet.command.to_string(),
                executor: client,
            });
        }
    }
}

#[allow(clippy::type_complexity)]
fn command_tree_update_with_client(
    command_registry: Res<CommandRegistry>,
    scope_registry: Res<CommandScopeRegistry>,
    mut updated_clients: Query<
        (&mut Client, &CommandScopes),
        Or<(Added<Client>, Changed<CommandScopes>)>,
    >,
) {
    update_client_command_tree(
        &command_registry,
        scope_registry,
        &mut updated_clients.iter_mut().collect(),
    );
}

fn update_command_tree(
    command_registry: Res<CommandRegistry>,
    scope_registry: Res<CommandScopeRegistry>,
    mut clients: Query<(&mut Client, &CommandScopes)>,
) {
    if command_registry.is_changed() {
        update_client_command_tree(
            &command_registry,
            scope_registry,
            &mut clients.iter_mut().collect(),
        );
    }
}

fn update_client_command_tree(
    command_registry: &Res<CommandRegistry>,
    scope_registry: Res<CommandScopeRegistry>,
    updated_clients: &mut Vec<(Mut<Client>, &CommandScopes)>,
) {
    for (ref mut client, client_scopes) in updated_clients {
        let time = std::time::Instant::now();

        let old_graph = &command_registry.graph;
        let mut new_graph = Graph::new();

        // collect a new graph into only nodes that are allowed to be executed
        let root = old_graph.root;

        let mut to_visit = vec![(None, root)];
        let mut already_visited = HashSet::new(); // prevent recursion
        let mut old_to_new = HashMap::new();
        let mut new_root = None;

        while let Some((parent, node)) = to_visit.pop() {
            if already_visited.contains(&(parent.map(|(node_id, _)| node_id), node)) {
                continue;
            }
            already_visited.insert((parent.map(|(node_id, _)| node_id), node));
            let node_scopes = &old_graph.graph[node].scopes;
            if !node_scopes.is_empty() {
                let mut has_scope = false;
                for scope in node_scopes {
                    if scope_registry.any_grants(
                        &client_scopes.0.iter().map(|scope| scope.as_str()).collect(),
                        scope,
                    ) {
                        has_scope = true;
                        break;
                    }
                }
                if !has_scope {
                    continue;
                }
            }

            let new_node = *old_to_new
                .entry(node)
                .or_insert_with(|| new_graph.add_node(old_graph.graph[node].clone()));

            for neighbor in old_graph.graph.edges_directed(node, Direction::Outgoing) {
                to_visit.push((Some((new_node, neighbor.weight())), neighbor.target()));
            }

            if let Some(parent) = parent {
                new_graph.add_edge(parent.0, new_node, *parent.1);
            } else {
                new_root = Some(new_node);
            }
        }

        match new_root {
            Some(new_root) => {
                let command_graph = CommandGraph {
                    graph: new_graph,
                    root: new_root,
                };
                let packet: CommandTreeS2c = command_graph.into();

                client.write_packet(&packet);
            }
            None => {
                warn!(
                    "Client has no permissions to execute any commands so we sent them nothing. \
                     It is generally a bad idea to scope the root node of the command graph as it \
                     can cause undefined behavior. For example, if the player has permission to \
                     execute a command before you change the scope of the root node, the packet \
                     will not be sent to the client and so the client will still think they can \
                     execute the command."
                )
            }
        }

        debug!("command tree update took {:?}", time.elapsed());
    }
}

fn parse_incoming_commands(
    mut event_reader: EventReader<CommandExecutionEvent>,
    mut event_writer: EventWriter<CommandProcessedEvent>,
    command_registry: Res<CommandRegistry>,
    scope_registry: Res<CommandScopeRegistry>,
    entity_scopes: Query<&CommandScopes>,
) {
    for command_event in event_reader.read() {
        let executor = command_event.executor;
        // these are the leafs of the graph that are executable under this command
        // group
        let executable_leafs = command_registry
            .executables
            .iter()
            .collect::<Vec<&NodeIndex>>();
        let root = command_registry.graph.root;

        let command_input = &*command_event.command;
        let graph = &command_registry.graph.graph;
        let input = ParseInput::new(command_input);

        let mut to_be_executed = Vec::new();

        let mut args = Vec::new();
        let mut modifiers_to_be_executed = Vec::new();

        parse_command_args(
            &mut args,
            &mut modifiers_to_be_executed,
            input,
            graph,
            &executable_leafs,
            command_registry.as_ref(),
            &mut to_be_executed,
            root,
            executor,
            &entity_scopes,
            scope_registry.as_ref(),
            false,
        );

        let mut modifiers = HashMap::new();
        for (node, modifier) in modifiers_to_be_executed {
            command_registry.modifiers[&node](modifier, &mut modifiers);
        }

        for node in to_be_executed {
            trace!("executing node: {node:?}");
            event_writer.send(CommandProcessedEvent {
                command: args.join(" "),
                executor,
                modifiers: modifiers.clone(),
                node,
            });
        }
        info!(
            "Command dispatched: /{} (debug logs for more data)",
            command_event.command
        );
        debug!("Command modifiers: {:?}", modifiers);
    }
}

#[allow(clippy::too_many_arguments)]
/// recursively parse the command args.
fn parse_command_args(
    command_args: &mut Vec<String>,
    modifiers_to_be_executed: &mut Vec<(NodeIndex, String)>,
    mut input: ParseInput,
    graph: &Graph<CommandNode, CommandEdgeType>,
    executable_leafs: &[&NodeIndex],
    command_registry: &CommandRegistry,
    to_be_executed: &mut Vec<NodeIndex>,
    current_node: NodeIndex,
    executor: Entity,
    scopes: &Query<&CommandScopes>,
    scope_registry: &CommandScopeRegistry,
    coming_from_redirect: bool,
) -> bool {
    let node_scopes = &graph[current_node].scopes;
    let default_scopes = CommandScopes::new();
    let client_scopes: Vec<&str> = scopes
        .get(executor)
        .unwrap_or(&default_scopes)
        .0
        .iter()
        .map(|scope| scope.as_str())
        .collect();
    // if empty, we assume the node is global
    if !node_scopes.is_empty() {
        let mut has_scope = false;
        for scope in node_scopes {
            if scope_registry.any_grants(&client_scopes, scope) {
                has_scope = true;
                break;
            }
        }
        if !has_scope {
            return false;
        }
    }

    if !coming_from_redirect {
        // we want to skip whitespace before matching the node
        input.skip_whitespace();
        match &graph[current_node].data {
            // no real need to check for root node
            NodeData::Root => {
                if command_registry.modifiers.contains_key(&current_node) {
                    modifiers_to_be_executed.push((current_node, String::new()));
                }
            }
            // if the node is a literal, we want to match the name of the literal
            // to the input
            NodeData::Literal { name } => {
                if input.match_next(name) {
                    if !input.match_next(" ") && !input.is_done() {
                        return false;
                    } // we want to pop the whitespace after the literal
                    if command_registry.modifiers.contains_key(&current_node) {
                        modifiers_to_be_executed.push((current_node, String::new()));
                    }
                } else {
                    return false;
                }
            }
            // if the node is an argument, we want to parse the argument
            NodeData::Argument { .. } => {
                let Some(parser) = command_registry.parsers.get(&current_node) else {
                    return false;
                };

                // we want to save the input before and after parsing
                // this is so we can save the argument to the command args
                let pre_input = input.clone().into_inner();
                let valid = parser(&mut input);
                if valid {
                    // If input.len() > pre_input.len() the parser replaced the input
                    let Some(arg) = pre_input
                        .get(..pre_input.len().wrapping_sub(input.len()))
                        .map(|s| s.to_owned())
                    else {
                        panic!(
                            "Parser replaced input with another string. This is not allowed. \
                             Attempting to parse: {}",
                            input.into_inner()
                        );
                    };

                    if command_registry.modifiers.contains_key(&current_node) {
                        modifiers_to_be_executed.push((current_node, arg.clone()));
                    }
                    command_args.push(arg);
                } else {
                    return false;
                }
            }
        }
    } else {
        command_args.clear();
    }

    input.skip_whitespace();
    if input.is_done() && executable_leafs.contains(&&current_node) {
        to_be_executed.push(current_node);
        return true;
    }

    let mut all_invalid = true;
    for neighbor in graph.neighbors(current_node) {
        let pre_input = input.clone();
        let mut args = command_args.clone();
        let mut modifiers = modifiers_to_be_executed.clone();
        let valid = parse_command_args(
            &mut args,
            &mut modifiers,
            input.clone(),
            graph,
            executable_leafs,
            command_registry,
            to_be_executed,
            neighbor,
            executor,
            scopes,
            scope_registry,
            {
                let edge = graph.find_edge(current_node, neighbor).unwrap();
                matches!(&graph[edge], CommandEdgeType::Redirect)
            },
        );
        if valid {
            *command_args = args;
            *modifiers_to_be_executed = modifiers;
            all_invalid = false;
        } else {
            input = pre_input;
        }
    }
    if all_invalid {
        return false;
    }
    true
}