use std::fmt::{Display, Formatter};

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

use crate::impl_from_uint_for;

/// Registered coin types for BIP-0044
///   https://github.com/satoshilabs/slips/blob/master/slip-0044.md
#[derive(
    Clone, CandidType, Hash, Debug, Ord, PartialOrd, Eq, PartialEq, Deserialize, Serialize,
)]
pub enum Chain {
    Bitcoin = 0,
    Ethereum = 60,
    Dfinity = 223,
    BnbChain = 714,
    EX3Layer2 = 87653426,
}

impl Display for Chain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Chain::Dfinity => write!(f, "Dfinity"),
            Chain::BnbChain => write!(f, "BnbChain"),
            Chain::Bitcoin => write!(f, "Bitcoin"),
            Chain::Ethereum => write!(f, "Ethereum"),
            Chain::EX3Layer2 => write!(f, "EX3Layer2"),
        }
    }
}

impl From<BigUint> for Chain {
    fn from(chain_id: BigUint) -> Self {
        match chain_id {
            chain_id if chain_id == Chain::Dfinity.into() => Chain::Dfinity,
            chain_id if chain_id == Chain::BnbChain.into() => Chain::BnbChain,
            chain_id if chain_id == Chain::Bitcoin.into() => Chain::Bitcoin,
            chain_id if chain_id == Chain::Ethereum.into() => Chain::Ethereum,
            chain_id if chain_id == Chain::EX3Layer2.into() => Chain::EX3Layer2,
            _ => panic!("unknown chain id"),
        }
    }
}

impl Into<BigUint> for Chain {
    fn into(self) -> BigUint {
        BigUint::from(self as u128)
    }
}

impl Chain {
    pub fn key_format(&self) -> KeyFormat {
        match self {
            Chain::Dfinity => KeyFormat::EcdsaSecp256k1,
            Chain::BnbChain => KeyFormat::EcdsaSecp256k1,
            Chain::Bitcoin => KeyFormat::EcdsaSecp256k1,
            Chain::Ethereum => KeyFormat::EcdsaSecp256k1,
            Chain::EX3Layer2 => KeyFormat::EcdsaSecp256k1,
        }
    }
}

impl_from_uint_for!(Chain, u8, u16, u32, u64, u128);

#[derive(
    Clone, CandidType, Hash, Debug, Ord, PartialOrd, Eq, PartialEq, Deserialize, Serialize,
)]
pub enum KeyFormat {
    EcdsaSecp256k1 = 0,
    Ed25519 = 1,
}

impl Display for KeyFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            KeyFormat::EcdsaSecp256k1 => write!(f, "EcdsaSecp256k1"),
            KeyFormat::Ed25519 => write!(f, "Ed25519"),
        }
    }
}

#[derive(
    Clone, CandidType, Hash, Debug, Ord, PartialOrd, Eq, PartialEq, Deserialize, Serialize,
)]
pub struct ChainIdentifier {
    pub chain: Chain,
    pub network: u8,
}

impl Storable for ChainIdentifier {
    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: 20,
        is_fixed_size: false,
    };
}


#[cfg(test)]
mod tests{
    use super::*;

    #[test]
    fn test_storable_for_chain_identifier() {
        let chain_identifier = ChainIdentifier {
            chain: Chain::EX3Layer2,
            network: u8::MAX,
        };
        let bytes = chain_identifier.to_bytes();
        assert!(bytes.len() <= 20, "bytes.len() = {}", bytes.len());
        let chain_identifier2 = ChainIdentifier::from_bytes(bytes);
        assert_eq!(chain_identifier, chain_identifier2);
    }
}