use_prelude!();
use super::DittoRegister;

/// Represents a mutable CRDT register that can be updated while updating a document.
///
/// This class can't be instantiated directly. It's returned from calls to
/// [`DittoMutDocument::get_mut`](crate::prelude::DittoMutDocument::get_mut).
pub struct DittoMutableRegister {
    document: *mut ffi_sdk::Document,
    path: char_p::Box,
    register: DittoRegister,
}

impl MutableValue for DittoMutableRegister {
    type BaseType = DittoRegister;
    fn mutable_version(
        base: Self::BaseType,
        document: &mut ffi_sdk::Document,
        path: char_p::Box,
    ) -> Result<Self> {
        Ok(Self {
            register: base,
            document,
            path,
        })
    }
}

impl DittoMutableRegister {
    /// Set content of the register to a new value.
    pub fn set<T: Serialize>(&mut self, value: T) -> Result<(), DittoError> {
        let path = self.path.clone();
        let document = self.document;
        // needed to get a ref mut to the document pointer
        unsafe {
            document.as_mut().unwrap().set(path.to_str(), &value)?;
        }

        let register = DittoRegister::new(value)?;
        self.register = register;
        Ok(())
    }

    /// Access to the value within the register.
    ///
    /// The operation may fail if the content of the register can not be serialized into `T`.
    pub fn value<T: DeserializeOwned>(self) -> Result<T, DittoError> {
        self.register.value()
    }
}
