// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use tokio::task::JoinHandle;

/**
 * Used by the `Game` to allow waiting for some tasks to finish before closing
 * the program. Useful for gracefully closing servers created by the GUI.
 */
pub struct FinalTasks(Vec<JoinHandle<()>>);

impl FinalTasks {
	pub fn new() -> FinalTasks {
		FinalTasks(Vec::new())
	}

	pub fn add(&mut self, task: JoinHandle<()>) {
		self.0.retain(|task| !task.is_finished()); // Cleans up finished tasks
		self.0.push(task);
	}

	pub async fn finish(self) {
		for task in self.0 {
			let _ = task.await;
		}
	}
}
