use crate::{core::Library, error::Result, utils::Id};
use serde::{Deserialize, Serialize};
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub enum Session {
Global,
Id(Id),
}
impl Session {
pub(crate) fn id(&self) -> Option<Id> {
match self {
Self::Id(id) => Some(*id),
Self::Global => None,
}
}
}
impl From<Id> for Session {
fn from(id: Id) -> Self {
Self::Id(id)
}
}
pub const GLOBAL: Session = Session::Global;
pub struct SessionsApi<'alex> {
pub(crate) inner: &'alex Library,
}
impl<'alex> SessionsApi<'alex> {
pub async fn list(&self) -> Vec<Id> {
vec![]
}
pub async fn open(&self, id: Id, pw: &str) -> Result<Session> {
let ref mut u = self.inner.users.write().await;
u.open(id, pw).map(|_| Session::Id(id))
}
pub async fn close(&self, id: Session) -> Result<()> {
if let Some(id) = id.id() {
let ref mut u = self.inner.users.write().await;
u.close(id)
} else {
Ok(())
}
}
pub async fn create(&self, id: Id, pw: &str) -> Result<Session> {
let ref mut u = self.inner.users.write().await;
u.insert(id, pw).map(|_| Session::Id(id))
}
pub async fn destroy(&self, id: Session) -> Result<()> {
if let Some(id) = id.id() {
let ref mut u = self.inner.users.write().await;
u.delete(id)
} else {
Ok(())
}
}
}