use std::collections::BTreeMap;
use laravel::model::{Changes, Model};
use crate::value::Attr;
static NULL: Attr = Attr::Null;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Record {
values: BTreeMap<String, Attr>,
}
impl Record {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, attribute: &str, value: impl Into<Attr>) -> Self {
self.values.insert(attribute.to_owned(), value.into());
self
}
pub fn of<M: Model>(model: &M) -> Self {
let values = M::META
.columns
.iter()
.map(|field| (field.name.to_owned(), Attr::from(&(field.value)(model))))
.collect();
Self { values }
}
pub fn before<M: Model>(model: &M, changes: &Changes<M>) -> Self {
let mut record = Self::of(model);
for change in changes {
record.values.insert(change.column.to_owned(), Attr::from(&change.old));
}
record
}
pub fn get(&self, attribute: &str) -> &Attr {
self.values.get(attribute).unwrap_or(&NULL)
}
pub fn text(&self, attribute: &str) -> Option<&str> {
self.get(attribute).as_text()
}
pub fn int(&self, attribute: &str) -> Option<i64> {
self.get(attribute).as_int()
}
pub fn bool(&self, attribute: &str) -> Option<bool> {
self.get(attribute).as_bool()
}
pub fn attributes(&self) -> impl Iterator<Item = &str> {
self.values.keys().map(String::as_str)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeKind {
Created,
Updated,
Deleted,
}
#[derive(Debug, Clone, Copy)]
pub struct Change<'a> {
pub kind: ChangeKind,
pub after: &'a Record,
pub before: Option<&'a Record>,
}
impl Change<'_> {
pub fn is(&self, attribute: &str) -> &Attr {
self.after.get(attribute)
}
pub fn was(&self, attribute: &str) -> &Attr {
self.before.map_or(&NULL, |before| before.get(attribute))
}
pub fn changed(&self, attributes: &[String]) -> bool {
let Some(before) = self.before else {
return true;
};
if attributes.is_empty() {
return before != self.after;
}
attributes
.iter()
.any(|attribute| !before.get(attribute).matches(self.after.get(attribute)))
}
pub fn became(&self, attribute: &str, to: &Attr) -> bool {
self.is(attribute).matches(to) && !self.was(attribute).matches(to)
}
pub fn left(&self, attribute: &str, from: &Attr) -> bool {
self.was(attribute).matches(from) && !self.is(attribute).matches(from)
}
pub fn holds(&self, attribute: &str, value: &Attr) -> bool {
self.is(attribute).matches(value)
}
pub fn held(&self, attribute: &str, value: &Attr) -> bool {
self.was(attribute).matches(value)
}
pub fn created(&self) -> bool {
self.kind == ChangeKind::Created
}
pub fn updated(&self) -> bool {
self.kind == ChangeKind::Updated
}
pub fn deleted(&self) -> bool {
self.kind == ChangeKind::Deleted
}
}