use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::destination::lock;
use super::draft::micros_z;
use crate::store::fileio::atomic_write;
use crate::store::time::Stamp;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Drops {
pub turns: u64,
pub bytes: u64,
pub first: Option<String>,
pub last: Option<String>,
}
fn path(landing: &Path) -> PathBuf {
landing.join("drops.json")
}
pub fn read(landing: &Path) -> Option<Drops> {
serde_json::from_slice(&fs::read(path(landing)).ok()?).ok()
}
pub fn add(landing: &Path, turns: u64, bytes: u64, now: Stamp) -> io::Result<()> {
let _held = lock(landing)?;
let mut drops = read(landing).unwrap_or_default();
let at = micros_z(now);
drops.turns += turns;
drops.bytes += bytes;
if drops.first.is_none() {
drops.first = Some(at.clone());
}
drops.last = Some(at);
let mut text = serde_json::to_string(&drops).expect("counts serialize");
text.push('\n');
atomic_write(&path(landing), &text, false)
}