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
use std::collections::HashMap;
use std::marker::PhantomData;

use bevy_app::{App, Plugin, PostStartup};
use bevy_ecs::change_detection::ResMut;
use bevy_ecs::event::{Event, EventReader, EventWriter};
use bevy_ecs::prelude::{Entity, IntoSystemConfigs, Resource};
use petgraph::prelude::NodeIndex;
use valence_server::EventLoopPreUpdate;

use crate::graph::CommandGraphBuilder;
use crate::modifier_value::ModifierValue;
use crate::parsers::ParseInput;
use crate::{
    Command, CommandProcessedEvent, CommandRegistry, CommandScopeRegistry, CommandSystemSet,
};

impl<T> Plugin for CommandHandlerPlugin<T>
where
    T: Command + Send + Sync + 'static,
{
    fn build(&self, app: &mut App) {
        app.add_event::<CommandResultEvent<T>>()
            .insert_resource(CommandResource::<T>::new())
            .add_systems(PostStartup, command_startup_system::<T>)
            .add_systems(
                EventLoopPreUpdate,
                command_event_system::<T>.after(CommandSystemSet),
            );
    }
}

pub struct CommandHandlerPlugin<T>
where
    T: Command,
{
    command: PhantomData<T>,
}

impl<T: Command> Default for CommandHandlerPlugin<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> CommandHandlerPlugin<T>
where
    T: Command,
{
    pub fn new() -> Self {
        CommandHandlerPlugin {
            command: PhantomData,
        }
    }
}

#[derive(Resource)]
struct CommandResource<T: Command + Send + Sync> {
    command: PhantomData<T>,
    executables: HashMap<NodeIndex, fn(&mut ParseInput) -> T>,
}

impl<T: Command + Send + Sync> CommandResource<T> {
    fn new() -> Self {
        CommandResource {
            command: PhantomData,
            executables: HashMap::new(),
        }
    }
}

#[derive(Event)]
pub struct CommandResultEvent<T>
where
    T: Command,
    T: Send + Sync + 'static,
{
    pub result: T,
    pub executor: Entity,
    pub modifiers: HashMap<ModifierValue, ModifierValue>,
}

fn command_startup_system<T>(
    mut registry: ResMut<CommandRegistry>,
    mut scope_registry: ResMut<CommandScopeRegistry>,
    mut command: ResMut<CommandResource<T>>,
) where
    T: Command + Send + Sync + 'static,
{
    let mut executables = HashMap::new();
    let mut parsers = HashMap::new();
    let mut modifiers = HashMap::new();
    let graph_builder = &mut CommandGraphBuilder::new(
        &mut registry,
        &mut executables,
        &mut parsers,
        &mut modifiers,
    );
    T::assemble_graph(graph_builder);
    graph_builder.apply_scopes(&mut scope_registry);

    command.executables.extend(executables.clone());
    registry.parsers.extend(parsers);
    registry.modifiers.extend(modifiers);
    registry.executables.extend(executables.keys());
}

/// This system reads incoming command events.
fn command_event_system<T>(
    mut commands_executed: EventReader<CommandProcessedEvent>,
    mut events: EventWriter<CommandResultEvent<T>>,
    command: ResMut<CommandResource<T>>,
) where
    T: Command + Send + Sync,
{
    for command_event in commands_executed.read() {
        if let Some(executable) = command.executables.get(&command_event.node) {
            let result = executable(&mut ParseInput::new(&command_event.command));
            events.send(CommandResultEvent {
                result,
                executor: command_event.executor,
                modifiers: command_event.modifiers.clone(),
            });
        }
    }
}