use candid::CandidType;
use ex3_serde::bincode::{deserialize, serialize};
use serde::{Deserialize, Serialize};

use ex3_canister_error::OtherError;

use crate::chain::Chain;
use crate::PublicKey;

#[derive(CandidType, Clone, Hash, Deserialize, Serialize, Debug, Eq, PartialEq)]
pub struct WalletIdentifier {
    pub chain: Chain,
    pub pub_key: PublicKey,
}

impl WalletIdentifier {
    pub fn encode(&self) -> Vec<u8> {
        serialize(&(&self.chain, &self.pub_key)).unwrap()
    }
    pub fn decode(bytes: &[u8]) -> Result<Self, OtherError> {
        let (chain, pub_key) =
            deserialize(bytes).map_err(|e| OtherError::new(format!("deserialize error: {}", e)))?;
        Ok(WalletIdentifier { chain, pub_key })
    }

    pub fn cbor_encode(&self) -> Vec<u8> {
        ex3_serde::cbor::serialize(self).unwrap()
    }

    pub fn cbor_decode(bytes: &[u8]) -> Result<Self, OtherError> {
        ex3_serde::cbor::deserialize(bytes)
            .map_err(|e| OtherError::new(format!("deserialize error: {}", e)))
    }
}
