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

use candid::CandidType;
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"),
        }
    }
}
