use crate::database::Store;
use crate::entities::Block;
use crate::error::RepositoryError;
use crate::types::EntityId;
use std::collections::HashMap as StdHashMap;
use super::block_repository::BlockRelationshipField;
use super::block_repository::BlockTable;
use super::block_repository::BlockTableRO;
fn read_field(block: &Block, field: &BlockRelationshipField) -> Vec<EntityId> {
match field {
BlockRelationshipField::List => block.list.into_iter().collect(),
}
}
fn write_field(block: &mut Block, field: &BlockRelationshipField, ids: Vec<EntityId>) {
match field {
BlockRelationshipField::List => block.list = ids.first().copied(),
}
}
pub struct BlockHashMapTable<'a> {
store: &'a Store,
}
impl<'a> BlockHashMapTable<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> BlockTable for BlockHashMapTable<'a> {
fn create(&mut self, entity: &Block) -> Result<Block, RepositoryError> {
self.create_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn create_multi(&mut self, entities: &[Block]) -> Result<Vec<Block>, RepositoryError> {
let mut created = Vec::with_capacity(entities.len());
let mut block_map = self.store.blocks.write().unwrap();
for entity in entities {
let new_entity = if entity.id == EntityId::default() {
let id = self.store.next_id("block");
Block {
id,
..entity.clone()
}
} else {
if block_map.contains_key(&entity.id) {
return Err(RepositoryError::DuplicateId {
entity: "Block",
id: entity.id,
});
}
entity.clone()
};
block_map.insert(new_entity.id, new_entity.clone());
created.push(new_entity);
}
Ok(created)
}
fn get(&self, id: &EntityId) -> Result<Option<Block>, RepositoryError> {
Ok(self.store.blocks.read().unwrap().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Block>>, RepositoryError> {
let map = self.store.blocks.read().unwrap();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Block>, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.values()
.cloned()
.collect())
}
fn update(&mut self, entity: &Block) -> Result<Block, RepositoryError> {
self.update_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn update_multi(&mut self, entities: &[Block]) -> Result<Vec<Block>, RepositoryError> {
let mut block_map = self.store.blocks.write().unwrap();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
let mut to_write = entity.clone();
if let Some(existing) = block_map.get(&entity.id) {
to_write.list = existing.list;
}
block_map.insert(entity.id, to_write.clone());
result.push(to_write);
}
Ok(result)
}
fn update_with_relationships(&mut self, entity: &Block) -> Result<Block, RepositoryError> {
self.update_with_relationships_multi(std::slice::from_ref(entity))
.map(|v| v.into_iter().next().unwrap())
}
fn update_with_relationships_multi(
&mut self,
entities: &[Block],
) -> Result<Vec<Block>, RepositoryError> {
let mut block_map = self.store.blocks.write().unwrap();
let mut result = Vec::with_capacity(entities.len());
for entity in entities {
block_map.insert(entity.id, entity.clone());
result.push(entity.clone());
}
Ok(result)
}
fn remove(&mut self, id: &EntityId) -> Result<(), RepositoryError> {
self.remove_multi(std::slice::from_ref(id))
}
fn remove_multi(&mut self, ids: &[EntityId]) -> Result<(), RepositoryError> {
let removed: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
{
let mut block_map = self.store.blocks.write().unwrap();
for id in ids {
block_map.remove(id);
}
}
{
let mut frame_map = self.store.frames.write().unwrap();
let updates: Vec<(EntityId, crate::entities::Frame)> = frame_map
.iter()
.filter_map(|(fid, f)| {
if f.blocks.iter().any(|bid| removed.contains(bid)) {
let mut updated = f.clone();
updated.blocks.retain(|bid| !removed.contains(bid));
updated.child_order.retain(|entry| {
if *entry > 0 {
!removed.contains(&(*entry as EntityId))
} else {
true
}
});
Some((*fid, updated))
} else {
None
}
})
.collect();
for (fid, f) in updates {
frame_map.insert(fid, f);
}
}
{
let mut runs = self.store.format_runs.write().unwrap();
for id in ids {
runs.remove(id);
}
}
{
let mut images = self.store.block_images.write().unwrap();
for id in ids {
images.remove(id);
}
}
Ok(())
}
fn get_relationship(
&self,
id: &EntityId,
field: &BlockRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.get(id)
.map(|b| read_field(b, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &BlockRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.blocks.read().unwrap();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|b| read_field(b, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &BlockRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.get(id)
.map(|b| read_field(b, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &BlockRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.get(id)
.map(|b| {
read_field(b, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &BlockRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
let map = self.store.blocks.read().unwrap();
let mut out = Vec::new();
for (id, block) in map.iter() {
let list = read_field(block, field);
if right_ids.iter().any(|rid| list.contains(rid)) {
out.push((*id, list));
}
}
Ok(out)
}
fn set_relationship_multi(
&mut self,
field: &BlockRelationshipField,
relationships: Vec<(EntityId, Vec<EntityId>)>,
) -> Result<(), RepositoryError> {
let mut map = self.store.blocks.write().unwrap();
for (id, ids) in relationships {
if let Some(block) = map.get_mut(&id) {
write_field(block, field, ids);
}
}
Ok(())
}
fn set_relationship(
&mut self,
id: &EntityId,
field: &BlockRelationshipField,
right_ids: &[EntityId],
) -> Result<(), RepositoryError> {
let mut map = self.store.blocks.write().unwrap();
if let Some(block) = map.get_mut(id) {
write_field(block, field, right_ids.to_vec());
}
Ok(())
}
fn move_relationship_ids(
&mut self,
id: &EntityId,
field: &BlockRelationshipField,
ids_to_move: &[EntityId],
new_index: i32,
) -> Result<Vec<EntityId>, RepositoryError> {
let mut map = self.store.blocks.write().unwrap();
let Some(block) = map.get_mut(id) else {
return Ok(Vec::new());
};
let current = read_field(block, field);
let moved = reorder(current, ids_to_move, new_index);
write_field(block, field, moved.clone());
Ok(moved)
}
}
pub struct BlockHashMapTableRO<'a> {
store: &'a Store,
}
impl<'a> BlockHashMapTableRO<'a> {
pub fn new(store: &'a Store) -> Self {
Self { store }
}
}
impl<'a> BlockTableRO for BlockHashMapTableRO<'a> {
fn get(&self, id: &EntityId) -> Result<Option<Block>, RepositoryError> {
Ok(self.store.blocks.read().unwrap().get(id).cloned())
}
fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Block>>, RepositoryError> {
let map = self.store.blocks.read().unwrap();
Ok(ids.iter().map(|id| map.get(id).cloned()).collect())
}
fn get_all(&self) -> Result<Vec<Block>, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.values()
.cloned()
.collect())
}
fn get_relationship(
&self,
id: &EntityId,
field: &BlockRelationshipField,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.get(id)
.map(|b| read_field(b, field))
.unwrap_or_default())
}
fn get_relationship_many(
&self,
ids: &[EntityId],
field: &BlockRelationshipField,
) -> Result<StdHashMap<EntityId, Vec<EntityId>>, RepositoryError> {
let map = self.store.blocks.read().unwrap();
let mut out = StdHashMap::new();
for id in ids {
out.insert(
*id,
map.get(id)
.map(|b| read_field(b, field))
.unwrap_or_default(),
);
}
Ok(out)
}
fn get_relationship_count(
&self,
id: &EntityId,
field: &BlockRelationshipField,
) -> Result<usize, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.get(id)
.map(|b| read_field(b, field).len())
.unwrap_or(0))
}
fn get_relationship_in_range(
&self,
id: &EntityId,
field: &BlockRelationshipField,
offset: usize,
limit: usize,
) -> Result<Vec<EntityId>, RepositoryError> {
Ok(self
.store
.blocks
.read()
.unwrap()
.get(id)
.map(|b| {
read_field(b, field)
.into_iter()
.skip(offset)
.take(limit)
.collect()
})
.unwrap_or_default())
}
fn get_relationships_from_right_ids(
&self,
field: &BlockRelationshipField,
right_ids: &[EntityId],
) -> Result<Vec<(EntityId, Vec<EntityId>)>, RepositoryError> {
let map = self.store.blocks.read().unwrap();
let mut out = Vec::new();
for (id, block) in map.iter() {
let list = read_field(block, field);
if right_ids.iter().any(|rid| list.contains(rid)) {
out.push((*id, list));
}
}
Ok(out)
}
}
fn reorder(current: Vec<EntityId>, ids_to_move: &[EntityId], new_index: i32) -> Vec<EntityId> {
if ids_to_move.is_empty() {
return current;
}
let move_set: std::collections::HashSet<EntityId> = ids_to_move.iter().copied().collect();
let mut remaining: Vec<EntityId> = current
.into_iter()
.filter(|eid| !move_set.contains(eid))
.collect();
let insert_pos = if new_index < 0 || (new_index as usize) > remaining.len() {
remaining.len()
} else {
new_index as usize
};
for (i, &eid) in ids_to_move.iter().enumerate() {
remaining.insert(insert_pos + i, eid);
}
remaining
}