use std::io;
use std::path::Path;
use std::time::SystemTime;
use super::destination::{self, Gate, key, stamp};
use super::files::{Part, entries};
use super::queue::Queue;
use super::serving::serving;
use super::slots;
use super::spawn::{Lander, spawn};
use super::state::{Destination, State, public_url};
use super::verb::conversations;
use crate::record::payload::{PROMPT_EVENT, RESPONSE_EVENT, SESSION_START_EVENT, STOP_EVENT};
use crate::record::settings::Settings;
use crate::remote::selection::Selection;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Event {
Stop,
Prompt,
SessionStart,
Tool,
}
impl Event {
pub fn of(name: &str) -> Self {
match name {
STOP_EVENT | RESPONSE_EVENT => Self::Stop,
PROMPT_EVENT => Self::Prompt,
SESSION_START_EVENT => Self::SessionStart,
_ => Self::Tool,
}
}
}
pub struct Hook<'a> {
pub home: &'a Path,
pub tree: &'a Path,
pub id: &'a str,
pub url: Option<&'a str>,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Found {
pub queued: bool,
pub blocked: bool,
pub waiting: bool,
}
impl Found {
pub fn queued(queued: bool) -> Self {
Self {
queued,
..Self::default()
}
}
}
pub fn starts(
event: Event,
found: Found,
slot: impl FnOnce() -> io::Result<bool>,
) -> io::Result<bool> {
if event == Event::Tool || !found.queued || found.blocked || found.waiting {
return Ok(false);
}
slot()
}
pub fn start(event: Event, found: Found, lander: &Lander) -> bool {
matches!(starts(event, found, || slots::free(lander.home)), Ok(true)) && spawn(lander).is_ok()
}
pub fn after(name: &str, closed: bool, hook: &Hook) -> bool {
let event = Event::of(name);
let found = match event {
Event::Stop if closed => queued(hook.tree, hook.home, hook.id),
Event::Prompt => queued(hook.tree, hook.home, hook.id),
Event::SessionStart => Found::queued(waits_here(hook.tree, hook.home, hook.url)),
Event::Stop | Event::Tool => Found::default(),
};
let own = [hook.home.join("spool"), hook.home.join("profile-spool")];
let lander = Lander {
home: hook.home,
spool: (!own.iter().any(|tree| tree == hook.tree)).then_some(hook.tree),
url: hook.url,
};
start(event, found, &lander)
}
pub fn queued(tree: &Path, home: &Path, id: &str) -> Found {
let directory = Queue::new(tree).pending_dir(id);
let Ok(listed) = entries(&directory) else {
return Found::default();
};
let (landing, now) = (slots::directory(home), stamp(SystemTime::now()));
let mut found = Found::default();
let turns = listed
.iter()
.filter(|(_, parts)| parts.iter().any(|(part, _)| *part == Part::Span));
for (n, _) in turns {
let state = State::read(&Queue::part(&directory, *n, "state"));
let Some(destination) = state.ok().and_then(|state| state.destination) else {
continue;
};
found.queued = true;
let record = destination::read(&landing, &key(&destination));
match record
.as_ref()
.map(|record| (record.gate(now), record.block.is_some()))
{
Some((Gate::Closed, true)) => found.blocked = true,
Some((Gate::Closed, false)) => found.waiting = true,
_ => return Found::queued(true),
}
}
found
}
pub fn direct(settings: &Settings, id: &str, name: &str, closed: bool) -> bool {
let Ok(home) = crate::home::home() else {
return false;
};
let url = handed(&settings.store);
let tree = &settings.spool;
after(
name,
closed,
&Hook {
home: &home,
tree,
id,
url,
},
)
}
pub fn profile(tree: &Path, id: &str, name: &str, closed: bool) -> bool {
let Some(home) = tree.parent() else {
return false;
};
after(
name,
closed,
&Hook {
home,
tree,
id,
url: None,
},
)
}
pub fn handed(selection: &Selection) -> Option<&str> {
match selection {
Selection::Remote { url, .. } if public_url(url) != url.trim_end_matches('/') => Some(url),
_ => None,
}
}
pub fn waits_here(tree: &Path, home: &Path, url: Option<&str>) -> bool {
let queue = Queue::new(tree);
let now = stamp(SystemTime::now());
let mut unservable: Vec<Destination> = Vec::new();
let Ok(ids) = conversations(tree) else {
return false;
};
for id in ids {
let directory = queue.pending_dir(&id);
let Ok(listed) = entries(&directory) else {
continue;
};
for n in listed.keys() {
let Ok(state) = State::read(&Queue::part(&directory, *n, "state")) else {
continue;
};
let Some(destination) = &state.destination else {
continue;
};
if unservable.contains(destination) {
continue;
}
let open = destination::gate(&slots::directory(home), destination, now) != Gate::Closed;
if open && serving(destination, &state, home, url).is_some() {
return true;
}
unservable.push(destination.clone());
}
}
false
}