// Copyright Marcus Del Favero 2025
// Licensed under the GNU AGPLv3 with an exception, see `README.md` for details
use std::sync::{Arc, Mutex};

use crate::net::serp::Error;

#[derive(Default, Clone)]
pub struct ErrorContainer(Arc<Mutex<Option<Error>>>);

impl ErrorContainer {
	/**
	 * Inserts an error if it's empty.
	 */
	pub fn insert(&self, error: Error) {
		let Ok(mut err) = self.0.lock() else { return; };
		*err = Some(error);
	}

	/**
	 * Gets an error, returning `Disconnected(None)` if nothing has been set.
	 */
	pub fn get(&self) -> Error {
		self.0.lock().map_or_else( // Shouldn't block for long
			|_| Error::Other(String::from("task panicked while setting error (shouldn't happen)")),
			|lock| (*lock).clone().unwrap_or(Error::Disconnected(None)),
		)
	}
}
