use candid::CandidType;
use ex3_ic_stable_structures::{storable::Bound, Storable};
use ex3_serde::bincode;
use serde::{Deserialize, Serialize};

use crate::{BlockHeight, CandidBlockHeight, CandidWalletRegisterId, PublicKey, WalletRegisterId};

#[derive(
    CandidType, Clone, Hash, Deserialize, Serialize, Debug, Eq, PartialEq, PartialOrd, Ord,
)]
pub struct WalletIdentifier(pub PublicKey);

impl WalletIdentifier {
    pub fn new(public_key: PublicKey) -> Self {
        Self(public_key)
    }
}

impl AsRef<PublicKey> for WalletIdentifier {
    fn as_ref(&self) -> &PublicKey {
        &self.0
    }
}

impl From<PublicKey> for WalletIdentifier {
    fn from(public_key: PublicKey) -> Self {
        Self(public_key)
    }
}

impl Storable for WalletIdentifier {
    fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
        self.0.as_ref().into()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        Self(PublicKey::from(bytes.as_ref()))
    }

    const BOUND: Bound = Bound::Unbounded;
}

#[derive(Clone, Hash, Deserialize, Serialize, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct RegisteredWalletIdentifier {
    pub wallet_id: WalletRegisterId,
    pub wallet_identifier: WalletIdentifier,
    pub registered_height: BlockHeight,
}

impl Storable for RegisteredWalletIdentifier {
    fn to_bytes(&self) -> std::borrow::Cow<[u8]> {
        bincode::serialize(self).unwrap().into()
    }

    fn from_bytes(bytes: std::borrow::Cow<[u8]>) -> Self {
        bincode::deserialize(bytes.as_ref()).unwrap()
    }

    const BOUND: Bound = Bound::Bounded {
        max_size: 192,
        is_fixed_size: false,
    };
}

#[derive(CandidType, Clone, Hash, Deserialize, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct CandidRegisteredWalletIdentifier {
    pub wallet_id: CandidWalletRegisterId,
    pub wallet_identifier: WalletIdentifier,
    pub registered_height: CandidBlockHeight,
}

impl From<RegisteredWalletIdentifier> for CandidRegisteredWalletIdentifier {
    fn from(registered_wallet_identifier: RegisteredWalletIdentifier) -> Self {
        Self {
            wallet_id: registered_wallet_identifier.wallet_id.into(),
            wallet_identifier: registered_wallet_identifier.wallet_identifier,
            registered_height: registered_wallet_identifier.registered_height.into(),
        }
    }
}

impl From<CandidRegisteredWalletIdentifier> for RegisteredWalletIdentifier {
    fn from(candid_registered_wallet_identifier: CandidRegisteredWalletIdentifier) -> Self {
        Self {
            wallet_id: candid_registered_wallet_identifier.wallet_id.into(),
            wallet_identifier: candid_registered_wallet_identifier.wallet_identifier,
            registered_height: candid_registered_wallet_identifier.registered_height.into(),
        }
    }
}
