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

use crate::{
    world::delegation::{
        auth_channel::{EntityAuthAccessor, EntityAuthChannel, EntityAuthMutator},
        entity_auth_status::{EntityAuthStatus, HostEntityAuthStatus},
    },
    HostType,
};

pub struct HostAuthHandler<E: Copy + Eq + Hash> {
    auth_channels: HashMap<E, (EntityAuthMutator, EntityAuthAccessor)>,
}

impl<E: Copy + Eq + Hash> HostAuthHandler<E> {
    pub fn new() -> Self {
        Self {
            auth_channels: HashMap::new(),
        }
    }

    pub fn register_entity(&mut self, host_type: HostType, entity: &E) -> EntityAuthAccessor {
        if self.auth_channels.contains_key(&entity) {
            panic!("Entity cannot register with Server more than once!");
        }

        let (mutator, accessor) = EntityAuthChannel::new_channel(host_type);

        self.auth_channels
            .insert(*entity, (mutator, accessor.clone()));

        accessor
    }

    pub fn deregister_entity(&mut self, entity: &E) {
        self.auth_channels.remove(&entity);
    }

    pub fn get_accessor(&self, entity: &E) -> EntityAuthAccessor {
        let (_, receiver) = self
            .auth_channels
            .get(&entity)
            .expect("Entity must be registered with Server before it can receive messages!");

        receiver.clone()
    }

    pub fn auth_status(&self, entity: &E) -> Option<HostEntityAuthStatus> {
        if let Some((_, receiver)) = self.auth_channels.get(&entity) {
            return Some(receiver.auth_status());
        }

        return None;
    }

    pub fn set_auth_status(&self, entity: &E, auth_status: EntityAuthStatus) {
        let (sender, _) = self
            .auth_channels
            .get(&entity)
            .expect("Entity must be registered with Server before it can be mutated!");

        sender.set_auth_status(auth_status);
    }
}