use std::cell::Cell;
use std::ptr::NonNull;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use block2::RcBlock;
use objc2_foundation::NSTimer;
use crate::engine::{DialogAnswer, PopupFeed, DIALOG_TIMEOUT};
thread_local! {
static OPEN: Cell<(u32, Option<Instant>, Duration)> = const { Cell::new((0, None, Duration::ZERO)) };
}
pub(super) fn open_time() -> Duration {
OPEN.with(|o| {
let (_, since, total) = o.get();
total + since.map_or(Duration::ZERO, |s| s.elapsed())
})
}
fn opened() {
OPEN.with(|o| {
let (n, since, total) = o.get();
o.set((n + 1, since.or_else(|| Some(Instant::now())), total));
});
}
fn closed() {
OPEN.with(|o| {
let (n, since, total) = o.get();
let n = n.saturating_sub(1);
if n == 0 {
o.set((
0,
None,
total + since.map_or(Duration::ZERO, |s| s.elapsed()),
));
} else {
o.set((n, since, total));
}
});
}
const POLL_SECS: f64 = 0.01;
pub(super) fn await_answer(
feed: Arc<PopupFeed>,
id: u64,
finish: Box<dyn Fn(Option<DialogAnswer>)>,
) {
let started = Instant::now();
opened();
let done = Rc::new(Cell::new(false));
let block = RcBlock::new(move |timer: NonNull<NSTimer>| {
if done.get() {
return;
}
let answer = feed.take_answer(id);
if answer.is_none() && started.elapsed() < DIALOG_TIMEOUT {
return;
}
done.set(true);
closed();
unsafe { timer.as_ref() }.invalidate();
finish(answer);
});
let _ =
unsafe { NSTimer::scheduledTimerWithTimeInterval_repeats_block(POLL_SECS, true, &block) };
}