use crate::{bridge::library::client as library_client, settings::WorkerSettings};
use indicatrix_net::library::{LibraryRequest, LibraryResponse};
use slint::{ComponentHandle, Weak};
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum LibrarySource {
#[default]
Local,
Remote(WorkerSettings),
}
impl LibrarySource {
#[must_use]
pub const fn is_remote(&self) -> bool {
matches!(self, Self::Remote(_))
}
#[must_use]
pub const fn worker(&self) -> Option<&WorkerSettings> {
match self {
Self::Remote(w) => Some(w),
Self::Local => None,
}
}
#[must_use]
pub fn label(&self) -> String {
match self {
Self::Local => "Local library".to_string(),
Self::Remote(w) => {
let name = if w.name.trim().is_empty() {
w.address.as_str()
} else {
w.name.as_str()
};
format!("Remote: {name}")
}
}
}
}
pub fn spawn_library_request<T, F>(
ui_weak: Weak<T>,
worker: WorkerSettings,
req: LibraryRequest,
on_done: F,
) where
T: ComponentHandle + 'static,
F: FnOnce(&T, Result<LibraryResponse, library_client::LibraryClientError>) + Send + 'static,
{
std::thread::spawn(move || {
let result = library_client::request(&worker, &req);
let _ = ui_weak.upgrade_in_event_loop(move |ui| on_done(&ui, result));
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_source_is_local() {
assert_eq!(LibrarySource::default(), LibrarySource::Local);
assert!(!LibrarySource::default().is_remote());
}
#[test]
fn local_has_no_worker_and_a_plain_label() {
let src = LibrarySource::Local;
assert_eq!(src.worker(), None);
assert_eq!(src.label(), "Local library");
}
#[test]
fn remote_reports_its_worker_and_is_remote() {
let worker = WorkerSettings {
name: "Office workstation".to_string(),
address: "10.0.0.5:9443".to_string(),
..WorkerSettings::default()
};
let src = LibrarySource::Remote(worker.clone());
assert!(src.is_remote());
assert_eq!(src.worker(), Some(&worker));
assert_eq!(src.label(), "Remote: Office workstation");
}
#[test]
fn remote_label_falls_back_to_address_when_unnamed() {
let worker = WorkerSettings {
name: String::new(),
address: "10.0.0.5:9443".to_string(),
..WorkerSettings::default()
};
let src = LibrarySource::Remote(worker);
assert_eq!(src.label(), "Remote: 10.0.0.5:9443");
}
}