use std::prelude::v1::*;
use std::collections::btree_map::{Iter, IterMut};
use serde::{Deserialize, Serialize };
use std::fmt::{ Debug };
use std::collections::BTreeMap;
use std::sync::Arc;
use parking_lot::Mutex;
use crate::{RegistryService, Service};
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Services {
service_map: BTreeMap<String, crate::RegistryService>,
key_map: BTreeMap<String, String>
}
impl Services {
pub fn new() -> Self {
Self {
service_map: BTreeMap::new(),
key_map: BTreeMap::new()
}
}
pub async fn add(&mut self, service_arc: Arc<dyn Service>) {
let identifier = service_arc.identifier();
let key = service_arc.key();
let registry_service = service_arc.register(service_arc.clone()).await;
self.service_map.insert(identifier.to_string(), registry_service);
self.key_map.insert(key.to_owned(), identifier.to_string());
match service_arc.init_service().await {
Ok(_) => {}
Err(_) => {}
}
}
pub async fn add_mut(&mut self, service_arc_mut: Arc<Mutex<dyn Service>>) {
let service_locked = service_arc_mut.try_lock_for(core::time::Duration::new(10, 0));
match service_locked {
Some(mut service_mut) => {
let identifier = service_mut.identifier();
let key = service_mut.key();
let registry_service = service_mut.register_mut(service_arc_mut.clone()).await;
self.service_map.insert(identifier.to_string(), registry_service);
self.key_map.insert(key.to_owned(), identifier.to_string());
match service_mut.init_service_mut().await {
Ok(_) => {}
Err(_) => {}
}
}
None => panic!("Failed to lock mut feature")
}
}
pub fn remove(&mut self, identifier: String) {
let service = self.service_map.remove(identifier.as_str());
match service {
None => (),
Some(s) => { self.key_map.remove(s.key.as_str()); }
};
}
pub fn get(&self, identifier: &str) -> Option<&RegistryService> {
self.service_map.get(identifier)
}
pub fn get_mut(&mut self, identifier: &str) -> Option<&mut RegistryService> {
self.service_map.get_mut(identifier)
}
pub fn find(&self, key: String) -> Option<&RegistryService> {
match self.key_map.get(key.as_str()) {
Some(result) => {
self.get(result.as_str())
},
None => None
}
}
pub fn list(&self) -> Iter<String, RegistryService> {
self.service_map.iter()
}
pub fn list_mut(&mut self) -> IterMut<String, RegistryService> {
self.service_map.iter_mut()
}
}