use crate::browser::cdp::{CdpClient, CdpSession};
use crate::error::{BrowsingError, Result};
use std::collections::HashMap;
use std::sync::Arc;
#[allow(dead_code)]
pub struct SessionGuard<'a> {
sessions: &'a HashMap<String, CdpSession>,
current_target_id: Option<&'a String>,
}
#[allow(dead_code)]
impl<'a> SessionGuard<'a> {
pub fn new(
sessions: &'a HashMap<String, CdpSession>,
current_target_id: Option<&'a String>,
) -> Self {
Self {
sessions,
current_target_id,
}
}
pub fn get_active_session(&self) -> Result<&'a CdpSession> {
self.current_target_id
.and_then(|id| self.sessions.get(id))
.ok_or_else(|| BrowsingError::Browser("No active session".to_string()))
}
pub fn get_client(&self) -> Result<Arc<CdpClient>> {
Ok(Arc::clone(&self.get_active_session()?.client))
}
pub fn get_session_id(&self) -> Result<&'a str> {
Ok(self.get_active_session()?.session_id.as_str())
}
pub fn has_active_session(&self) -> bool {
self.current_target_id
.is_some_and(|id| self.sessions.contains_key(id))
}
pub fn current_target_id(&self) -> Option<&'a str> {
self.current_target_id.map(|s| s.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_no_active_session() {
let sessions = HashMap::new();
let guard = SessionGuard::new(&sessions, None);
assert!(guard.get_active_session().is_err());
assert!(!guard.has_active_session());
}
#[test]
fn test_with_active_session() {
let mut sessions = HashMap::new();
let target_id = "test-target".to_string();
let guard = SessionGuard::new(&sessions, Some(&target_id));
assert!(guard.get_active_session().is_err()); assert!(!guard.has_active_session());
}
}