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
use std::{collections::HashMap, fmt::Debug};

use bevy_ecs::{
	prelude::*,
	schedule::{IntoSystemDescriptor, ShouldRun, StateData},
	system::Resource,
};

enum Hook {
	Enter,
	Exit,
	Pause,
	Resume,
}

/// Function used to generate the function used for the run condition
pub fn in_state<T: PartialEq + Resource>(state: T) -> impl Fn(Res<TopState<T>>) -> ShouldRun {
	move |res| {
		if res.0 == state {
			ShouldRun::Yes
		} else {
			ShouldRun::No
		}
	}
}

mod r#trait;
pub use r#trait::AppStateStackExt;

pub struct TopState<T: PartialEq>(pub T);

impl<T: PartialEq + Debug> Debug for TopState<T> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "TopState({:?})", self.0)
	}
}

/// Resource to change the stack
pub enum Stack<T> {
	/// Replace the top level of the state stack.
	Set(T),
	/// Push another state on top of the stack.
	Push(T),
	/// Pop the top of the state at the top of the stack.
	Pop,
}

struct StackStage<T: StateData> {
	enter_stages: HashMap<T, Box<dyn Stage>>,
	resume_stages: HashMap<T, Box<dyn Stage>>,
	exit_stages: HashMap<T, Box<dyn Stage>>,
	pause_stages: HashMap<T, Box<dyn Stage>>,
	stack: Vec<T>,
}

impl<T: StateData> StackStage<T> {
	fn add_system<Params>(&mut self, h: Hook, state: T, system: impl IntoSystemDescriptor<Params>) {
		let map = match h {
			Hook::Enter => &mut self.enter_stages,
			Hook::Exit => &mut self.exit_stages,
			Hook::Pause => &mut self.pause_stages,
			Hook::Resume => &mut self.resume_stages,
		};

		if let Some(stage) = map.get_mut(&state) {
			stage
				.downcast_mut::<SystemStage>()
				.expect("State is not a SystemStage! This should be impossible!")
				.add_system(system);
		} else {
			let mut stage = SystemStage::parallel();
			stage.add_system(system);
			map.insert(state.clone(), Box::new(stage));
		}
	}

	fn new(init: T) -> Self {
		Self {
			enter_stages: Default::default(),
			exit_stages: Default::default(),
			pause_stages: Default::default(),
			resume_stages: Default::default(),
			stack: vec![init],
		}
	}
}

impl<T: StateData> Stage for StackStage<T> {
	fn run(&mut self, world: &mut World) {
		if !world.contains_resource::<TopState<T>>() {
			let init = &self.stack[0];
			world.insert_resource(TopState(init.clone()));

			if let Some(stage) = self.enter_stages.get_mut(init) {
				stage.run(world);
			}
		}

		if let Some(change) = world.remove_resource::<Stack<T>>() {
			let cur = &world.get_resource::<TopState<T>>().unwrap().0;
			match change {
				Stack::Set(s) => {
					// exit the current stage
					if let Some(stage) = self.exit_stages.get_mut(cur) {
						stage.run(world);
					}

					world.insert_resource(TopState(s.clone()));

					// enter the new stage
					if let Some(stage) = self.enter_stages.get_mut(&s) {
						stage.run(world);
					}

					let last = self.stack.last_mut().unwrap();
					*last = s;
				}
				Stack::Push(s) => {
					// pause the current stage
					if let Some(stage) = self.pause_stages.get_mut(cur) {
						stage.run(world);
					}

					world.insert_resource(TopState(s.clone()));

					// enter the new stage
					if let Some(stage) = self.enter_stages.get_mut(&s) {
						stage.run(world);
					}

					self.stack.push(s)
				}
				Stack::Pop => {
					if self.stack.len() == 1 {
						eprintln!("Can't pop the only state in stack!")
					} else {
						println!("pop");
						if let Some(stage) = self.exit_stages.get_mut(cur) {
							stage.run(world);
						}

						self.stack.pop();

						let state = self.stack.last().unwrap();

						if let Some(stage) = self.resume_stages.get_mut(state) {
							stage.run(world);
						}

						world.insert_resource(TopState(state.clone()))
					}
				}
			}
		}
	}
}