use super::NetSession;
use std::sync::{
    atomic::{AtomicU64, Ordering},
    Arc,
};

use dashmap::DashMap;
use tokio::net::TcpStream;

pub struct NetSessionManager {
    sessions: DashMap<u64, Arc<NetSession>>,
    id_counter: AtomicU64,
}

impl NetSessionManager {
    pub fn new() -> Self {
        Self {
            sessions: DashMap::new(),
            id_counter: AtomicU64::new(1),
        }
    }

    pub fn create(&self, stream: TcpStream) -> Arc<NetSession> {
        let id = self.id_counter.fetch_add(1, Ordering::SeqCst);
        let session = Arc::new(NetSession::new(id, stream));
        self.sessions.insert(id, session.clone());

        session
    }

    pub fn get(&self, id: u64) -> Option<Arc<NetSession>> {
        self.sessions.get(&id).map(|s| (*s).clone())
    }

    pub fn remove(&self, id: u64) {
        self.sessions.remove(&id);
    }
}
