use super::super::doubt::WENT_QUIET;
use super::super::{Call, Capture};
use super::{Mailbox, Slots, lock_mail};
pub(super) type Key = (String, String, String);
const OWN: &str = "";
#[derive(Default)]
pub(super) struct Asked {
pub(super) at: i64,
flight: Option<String>,
last: Option<Capture>,
}
fn key(call: &Call) -> Key {
(
call.client.clone(),
call.tool.clone(),
call.input.to_string(),
)
}
impl Slots {
fn busy(&self, now: i64, client: &str) -> bool {
self.live
.values()
.any(|slot| slot.client == client && slot.works(now))
}
fn settle(&mut self, now: i64, key: &Key) -> bool {
let read = self.known.entry(key.clone()).or_default();
read.at = now;
let Some(id) = read.flight.clone() else {
return false;
};
let landed = self
.live
.get_mut(&id)
.and_then(|slot| {
slot.heard = now;
if slot.run.silent(now) {
slot.doubt(WENT_QUIET);
}
slot.run.answer(None)
})
.map(|standing| standing.capture);
if landed == Some(None) {
return true;
}
self.live.remove(&id);
if let Some(capture) = landed.flatten() {
read.last = Some(capture);
}
read.flight = None;
false
}
}
impl Mailbox {
pub fn busy(&self, now: i64, client: &str) -> bool {
lock_mail(&self.cell).busy(now, client)
}
pub fn ask(&self, now: i64, call: &Call) {
let (mut slots, read) = (lock_mail(&self.cell), key(call));
if !slots.settle(now, &read) {
let id = slots.queue(now, OWN, call);
slots.known.entry(read).or_default().flight = Some(id);
}
}
pub fn queued(&self, now: i64, call: &Call) -> bool {
lock_mail(&self.cell).settle(now, &key(call))
}
pub fn known(&self, call: &Call) -> Option<Capture> {
let slots = lock_mail(&self.cell);
slots
.known
.get(&key(call))
.and_then(|read| read.last.clone())
}
}