use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use async_trait::async_trait;
use mf_model::mark::Mark;
use mf_model::node_type::NodeEnum;
use mf_model::types::NodeId;
use mf_transform::TransformResult;
use serde_json::Value;
use super::state::State;
use mf_model::node_pool::NodePool;
use mf_transform::attr_step::AttrStep;
use mf_transform::node_step::{AddNodeStep, RemoveNodeStep};
use mf_transform::mark_step::{AddMarkStep, RemoveMarkStep};
use mf_transform::transform::{Transform};
use std::fmt::Debug;
static IDS: AtomicU64 = AtomicU64::new(1);
pub fn get_transaction_id() -> u64 {
IDS.fetch_add(1, Ordering::SeqCst)
}
#[async_trait]
pub trait Command: Send + Sync + Debug {
async fn execute(
&self,
tr: &mut Transaction,
) -> TransformResult<()>;
fn name(&self) -> String;
}
#[derive(Debug, Clone)]
pub struct Transaction {
pub meta: im::HashMap<String, Arc<dyn std::any::Any>>,
pub id: u64,
transform: Transform,
}
unsafe impl Send for Transaction {}
unsafe impl Sync for Transaction {}
impl Deref for Transaction {
type Target = Transform;
fn deref(&self) -> &Self::Target {
&self.transform
}
}
impl DerefMut for Transaction {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.transform
}
}
impl Transaction {
pub fn new(state: &State) -> Self {
let node = state.doc();
let schema = state.schema();
Transaction {
meta: im::HashMap::new(),
id: get_transaction_id(),
transform: Transform::new(node, schema),
}
}
pub fn merge(
&mut self,
other: &mut Self,
) {
let steps_to_apply: Vec<_> = other.steps.iter().cloned().collect();
if let Err(e) = self.apply_steps_batch(steps_to_apply) {
eprintln!("批量应用步骤失败: {}", e);
}
}
pub fn doc(&self) -> Arc<NodePool> {
self.transform.doc()
}
pub fn set_node_attribute(
&mut self,
id: String,
values: im::HashMap<String, Value>,
) -> TransformResult<()> {
self.step(Arc::new(AttrStep::new(id, values)))?;
Ok(())
}
pub fn add_node(
&mut self,
parent_id: NodeId,
nodes: Vec<NodeEnum>,
) -> TransformResult<()> {
self.step(Arc::new(AddNodeStep::new(parent_id, nodes)))?;
Ok(())
}
pub fn remove_node(
&mut self,
parent_id: NodeId,
node_ids: Vec<NodeId>,
) -> TransformResult<()> {
self.step(Arc::new(RemoveNodeStep::new(parent_id, node_ids)))?;
Ok(())
}
pub fn add_mark(
&mut self,
id: NodeId,
marks: Vec<Mark>,
) -> TransformResult<()> {
self.step(Arc::new(AddMarkStep::new(id, marks)))?;
Ok(())
}
pub fn remove_mark(
&mut self,
id: NodeId,
mark_types: Vec<String>,
) -> TransformResult<()> {
self.step(Arc::new(RemoveMarkStep::new(id, mark_types)))?;
Ok(())
}
pub fn set_meta<K, T: std::any::Any>(
&mut self,
key: K,
value: T,
) -> &mut Self
where
K: Into<String>,
{
let key_str = key.into();
self.meta.insert(key_str, Arc::new(value));
self
}
pub fn get_meta<T: 'static>(
&self,
key: &str,
) -> Option<&Arc<T>> {
self.meta.get(key)?.downcast_ref::<Arc<T>>()
}
}