#![allow(deprecated)]

use_prelude!();
use super::DittoRegister;

/// Use [`doc.get_mut::<DittoMutableRegister>("...")`] to obtain a mutable
/// CRDT register.
///
/// A mutable CRDT register can be updated while updating a document using
/// [`.pending_cursor_op.update(...)`] or [`.pending_id_op.update(...)`].
///
/// [`doc.get_mut::<DittoMutableRegister>("...")`]: crate::prelude::DittoMutDocument::get_mut
/// [`.pending_cursor_op.update(...)`]: crate::store::query_builder::PendingCursorOperation::update
/// [`.pending_id_op.update(...)`]: crate::store::query_builder::PendingIdSpecificOperation::update
#[deprecated(
    since = "4.14.4",
    note = "Will be removed in SDK 5.0. Use DQL queries instead"
)]
pub struct DittoMutableRegister<'doc> {
    document: &'doc mut ffi_sdk::Document,
    path: char_p::Box,
    register: DittoRegister,
}

impl<'doc> MutableValue<'doc> for DittoMutableRegister<'doc> {
    type BaseType = DittoRegister;
    fn mutable_version(
        base: Self::BaseType,
        document: &'doc 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();
        self.document.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()
    }
}
