use candid::{CandidType, Deserialize};
use ex3_canister_types::chain::Chain;
use ex3_node_error::OtherError;
use ex3_serde::bincode::{deserialize, serialize};
use num_bigint::BigUint;
use serde::Serialize;

/// Token type
///  * Different chain have different token type
#[derive(CandidType, Debug, Clone, Hash, Deserialize, Serialize, PartialEq, Eq)]
pub enum TokenType {
    Bitcoin,
    EVM(EVMTokenType),
    Dfinity(DfinityTokenType),
}

/// EVM token type
/// * Dfinity
/// * ERC20
/// * ERC721
#[derive(CandidType, Debug, Clone, Hash, Deserialize, Serialize, PartialEq, Eq)]
pub enum EVMTokenType {
    Native,
    ERC20,
    ERC721,
}

/// Dfinity token type
#[derive(CandidType, Debug, Clone, Hash, Deserialize, Serialize, PartialEq, Eq)]
pub enum DfinityTokenType {
    /// Dfinity
    ICP,
    /// Cycles
    Cycles,
    DFT,
    ICRC1,
}

/// crypto asset
#[derive(CandidType, Debug, Clone, Hash, PartialEq, Eq)]
pub struct CryptoAsset {
    pub chain: Chain,
    pub r#type: TokenType,
    pub address: Option<String>,
}

impl CryptoAsset {
    pub fn encode(&self) -> Vec<u8> {
        serialize(&(&self.chain, &self.r#type, &self.address)).unwrap()
    }
}

impl TryFrom<&[u8]> for CryptoAsset {
    type Error = OtherError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let (chain, token_type, token_id) = deserialize(value).map_err(|e| {
            OtherError::new(format!(
                "Failed to deserialize CryptoAsset from bytes: {:?}",
                e
            ))
        })?;
        Ok(CryptoAsset {
            chain,
            r#type: token_type,
            address: token_id,
        })
    }
}

impl std::fmt::Display for CryptoAsset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let token_type = match &self.r#type {
            TokenType::Bitcoin => "Bitcoin",
            TokenType::EVM(token_type) => match token_type {
                EVMTokenType::Native => "Native",
                EVMTokenType::ERC20 => "ERC20",
                EVMTokenType::ERC721 => "ERC721",
            },
            TokenType::Dfinity(token_type) => match token_type {
                DfinityTokenType::ICP => "ICP",
                DfinityTokenType::Cycles => "Cycles",
                DfinityTokenType::DFT => "DFT",
                DfinityTokenType::ICRC1 => "ICRC1",
            },
            // TODO: add more token type
        };

        write!(
            f,
            "{}{}{}",
            Into::<BigUint>::into(self.chain.clone()),
            token_type,
            self.address.as_ref().unwrap_or(&"".to_string())
        )
    }
}
