use serde::Serialize;

use crate::Record;

#[derive(Clone, Debug, Serialize)]
pub struct Entry<Val: Record + Serialize>
where
    Val::SelfId: Serialize,
{
    // #[serde(rename = "id")]
    #[serde(flatten)]
    pub key: Val::SelfId,
    #[serde(flatten)]
    pub val: Val,
}

impl<Val: Record + Serialize> Entry<Val>
where
    Val::SelfId: Serialize,
{
    pub fn new(key: Val::SelfId, val: Val) -> Self {
        Entry { key, val }
    }

    pub fn get_id(self) -> Val::SelfId {
        self.key
    }
    pub fn get_val(&self) -> &Val {
        &self.val
    }
    pub fn split(self) -> (Val::SelfId, Val) {
        let Entry { key, val } = self;
        (key, val)
    }
    pub fn as_tuple(&self) -> (Val::SelfId, &Val) {
        let Entry { key, val } = self;
        (*key, val)
    }
}

impl<Val: Record + Serialize> From<(Val::SelfId, Val)> for Entry<Val>
where
    Val::SelfId: Serialize,
{
    fn from(tuple: (Val::SelfId, Val)) -> Self {
        Entry::new(tuple.0, tuple.1)
    }
}
