use chrono::{DateTime, Local};
use std::collections::BTreeMap;
use traits::{AutoEncoder, Body};
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum Payload {
Text(String),
Boolean(bool),
Number(i64),
BTreeMap(BTreeMap<String, Payload>),
List(Vec<Payload>),
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct Header {
pub name: String,
pub category: String,
pub tags: Vec<String>,
pub fields: BTreeMap<String, Payload>,
pub date_created: DateTime<Local>,
pub date_updated: DateTime<Local>,
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct Record<T: Body> {
pub header: Header,
#[serde(bound(deserialize = "T: Body"))]
pub body: Option<T>,
}
impl<T: Body> Record<T> {
pub fn new(name: &str, category: &str, tags: Vec<&str>) -> Self {
Record {
header: Header {
name: name.to_owned(),
category: category.to_owned(),
tags: tags.into_iter().map(|s| s.to_owned()).collect(),
fields: BTreeMap::new(),
date_created: Local::now(),
date_updated: Local::now(),
},
body: None,
}
}
pub fn add_data(&mut self, key: &str, value: Payload) -> Option<()> {
(self.body.as_mut()?).set_field(key, value);
Some(())
}
pub fn get_data(&self, key: &str) -> Option<&Payload> {
(self.body.as_ref()?).get_field(key)
}
}
impl<T: Body> AutoEncoder for Record<T> {}
#[derive(Serialize, Deserialize)]
pub struct EncryptedBody {
pub data: String,
}
impl Body for EncryptedBody {
fn get_field(&self, _: &str) -> Option<&Payload> {
None
}
fn set_field(&mut self, _: &str, _: Payload) -> Option<()> {
None
}
fn flatten(&mut self) -> Option<()> {
None
}
}