//! Useful extras for `Account` state.

use std::cell::Ref;

use bincode::ErrorKind;
use rialo_s_instruction::error::InstructionError;

use crate::{Account, AccountSharedData, StoredAccount};

/// Convenience trait to covert bincode errors to instruction errors.
pub trait StateMut<T> {
    fn state(&self) -> Result<T, InstructionError>;
    fn set_state(&mut self, state: &T) -> Result<(), InstructionError>;
}
pub trait State<T> {
    fn state(&self) -> Result<T, InstructionError>;
    fn set_state(&self, state: &T) -> Result<(), InstructionError>;
}

impl<T> StateMut<T> for Account
where
    T: serde::Serialize + serde::de::DeserializeOwned,
{
    fn state(&self) -> Result<T, InstructionError> {
        self.deserialize_data()
            .map_err(|_| InstructionError::InvalidAccountData)
    }
    fn set_state(&mut self, state: &T) -> Result<(), InstructionError> {
        self.serialize_data(state).map_err(|err| match *err {
            ErrorKind::SizeLimit => InstructionError::AccountDataTooSmall,
            _ => InstructionError::GenericError,
        })
    }
}

impl<T> StateMut<T> for AccountSharedData
where
    T: serde::Serialize + serde::de::DeserializeOwned,
{
    fn state(&self) -> Result<T, InstructionError> {
        self.deserialize_data()
            .map_err(|_| InstructionError::InvalidAccountData)
    }
    fn set_state(&mut self, state: &T) -> Result<(), InstructionError> {
        self.serialize_data(state).map_err(|err| match *err {
            ErrorKind::SizeLimit => InstructionError::AccountDataTooSmall,
            _ => InstructionError::GenericError,
        })
    }
}

impl<T> StateMut<T> for Ref<'_, AccountSharedData>
where
    T: serde::Serialize + serde::de::DeserializeOwned,
{
    fn state(&self) -> Result<T, InstructionError> {
        self.deserialize_data()
            .map_err(|_| InstructionError::InvalidAccountData)
    }
    fn set_state(&mut self, _state: &T) -> Result<(), InstructionError> {
        panic!("illegal");
    }
}

impl<T> StateMut<T> for StoredAccount
where
    T: serde::Serialize + serde::de::DeserializeOwned,
{
    fn state(&self) -> Result<T, InstructionError> {
        match self {
            StoredAccount::Data(account) => account.state(),
            StoredAccount::Balance(_) => {
                // Balance accounts typically don't have serialized state
                Err(InstructionError::InvalidAccountData)
            }
            StoredAccount::Executable(executable) => bincode::deserialize(&executable.data)
                .map_err(|_| InstructionError::InvalidAccountData),
        }
    }
    fn set_state(&mut self, state: &T) -> Result<(), InstructionError> {
        match self {
            StoredAccount::Data(account) => account.set_state(state),
            StoredAccount::Balance(_) => {
                // Balance accounts typically don't have serialized state
                Err(InstructionError::InvalidAccountData)
            }
            StoredAccount::Executable(_) => {
                // Executable accounts are immutable
                Err(InstructionError::InvalidAccountData)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use rialo_s_pubkey::Pubkey;

    use super::*;

    #[test]
    fn test_account_state() {
        let state = 42u64;

        assert!(AccountSharedData::default().set_state(&state).is_err());
        let res = AccountSharedData::default().state() as Result<u64, InstructionError>;
        assert!(res.is_err());

        let mut account = AccountSharedData::new(0, std::mem::size_of::<u64>(), &Pubkey::default());

        assert!(account.set_state(&state).is_ok());
        let stored_state: u64 = account.state().unwrap();
        assert_eq!(stored_state, state);
    }
}
