use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::error::DittoError;

#[deprecated(
    since = "4.14.4",
    note = "Will be removed in SDK 5.0. Use DQL queries instead"
)]
#[derive(Serialize, Deserialize, Debug)]
pub struct DittoRegisterStoredFormat {
    _value: serde_json::Value,
    #[serde(rename = "_ditto_internal_type_jkb12973t4b")]
    _type: u64,
}

/// Use [`doc.get::<DittoRegister>("...")`] to obtain a read-only CRDT register.
///
/// Represents a CRDT register that can be upserted as part of a document or
/// assigned to a property during an update of a document.
///
/// [`doc.get::<DittoRegister>("...")`]: crate::store::query_builder::DittoDocument::get
#[deprecated(
    since = "4.14.4",
    note = "Will be removed in SDK 5.0. Use DQL queries instead"
)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(from = "serde_json::Value", into = "DittoRegisterStoredFormat")]
pub struct DittoRegister {
    pub value: serde_json::Value,
}

impl From<serde_json::Value> for DittoRegister {
    fn from(value: serde_json::Value) -> DittoRegister {
        DittoRegister { value }
    }
}

impl From<DittoRegister> for DittoRegisterStoredFormat {
    fn from(DittoRegister { value }: DittoRegister) -> DittoRegisterStoredFormat {
        Self {
            _value: value,
            _type: ::ffi_sdk::DittoCrdtType::Register as u64,
        }
    }
}

impl DittoRegister {
    /// Create a new register with the provided value
    pub fn new<T: Serialize>(value: T) -> Result<Self, DittoError> {
        let value = serde_json::to_value(value)?;
        Ok(Self { value })
    }

    /// 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> {
        serde_json::from_value(self.value.clone()).map_err(|json_err| json_err.into())
    }
}
