use tokio_util::sync::CancellationToken;
use super::WhatsAppState;
const PHOTO_DEBOUNCE: std::time::Duration = std::time::Duration::from_secs(3);
impl WhatsAppState {
pub async fn buffer_photo(
&self,
chat_jid: &str,
img_marker: String,
caption: Option<String>,
) -> usize {
let mut buffer = self.photo_buffer.lock().await;
let entry = buffer.entry(chat_jid.to_string()).or_default();
entry.push((img_marker, caption));
entry.len()
}
pub async fn drain_photo_buffer(&self, chat_jid: &str) -> (Vec<String>, Option<String>) {
let mut buffer = self.photo_buffer.lock().await;
if let Some(entries) = buffer.remove(chat_jid) {
let caption = entries
.iter()
.find_map(|(_, c)| c.as_ref().filter(|s| !s.trim().is_empty()).cloned());
let markers: Vec<String> = entries.into_iter().map(|(m, _)| m).collect();
(markers, caption)
} else {
(Vec::new(), None)
}
}
pub async fn reset_photo_debounce(&self, chat_jid: &str) -> CancellationToken {
let mut debounce = self.photo_debounce.lock().await;
if let Some(old_token) = debounce.remove(chat_jid) {
old_token.cancel();
}
let token = CancellationToken::new();
debounce.insert(chat_jid.to_string(), token.clone());
token
}
pub async fn wait_photo_debounce(&self, token: &CancellationToken) -> bool {
tokio::select! {
_ = token.cancelled() => false,
_ = tokio::time::sleep(PHOTO_DEBOUNCE) => true,
}
}
pub async fn cleanup_photo_debounce(&self, chat_jid: &str) {
let mut debounce = self.photo_debounce.lock().await;
debounce.remove(chat_jid);
}
}