use candid::{CandidType, Deserialize, Nat};
use num_bigint::BigUint;
use serde::Serialize;

use crate::{
    AssetAmount, AssetId, CandidAssetAmount, CandidAssetId, CandidMarketId, CandidWalletRegisterId,
    MarketId, WalletRegisterId,
};

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct SpotMarket {
    /// Market id
    pub id: MarketId,

    /// Base asset id
    pub base_asset_id: AssetId,

    /// Quote asset id
    pub quote_asset_id: AssetId,

    /// Market trading settings
    pub trading_settings: SpotMarketTradingSettings,

    /// Fee
    /// Trading fee
    pub fee: SpotMarketTradingFee,

    /// Fee to
    /// Trading fee to
    pub fee_to: WalletRegisterId,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SpotMarketTradingFee {
    /// Orderbook taker fee
    /// Swap fee is the same as orderbook taker fee
    pub taker_fee: BigUint,

    /// Orderbook maker fee
    pub maker_fee: BigUint,

    /// AMM V2 fee taking ratio
    /// # Range
    /// 0 ~ 100
    /// # Example
    /// * 0: 0%
    /// * 100: 100%
    /// # Note
    /// This value is used for AMM V2
    pub amm_v2_fee_taking_ratio: BigUint,

    /// Fee decimal for
    /// * `taker_fee` & `maker_fee` & `amm_v2_fee_taking_ratio`
    pub fee_decimal: u8,
}

/// Orderbook price limitation
/// # Example
/// ```rust
/// use std::ops::Mul;
/// use num_bigint::BigUint;
/// use ex3_node_types::market::SpotOrderPriceLimitation;
/// let latest_order_price: BigUint = BigUint::from(1000000000u32);
/// let order_price_limitation = SpotOrderPriceLimitation {
///    bid_price_rate_cap: BigUint::from(300000000u32),
///    ask_price_rate_floor: BigUint::from(20000000u32),
///    rate_decimal: 8,
/// };
/// let real_bid_price_rate_cap  = order_price_limitation.bid_price_rate_cap.clone()
///         / BigUint::from(10u32.pow(order_price_limitation.rate_decimal.clone() as u32));
/// assert_eq!(real_bid_price_rate_cap, BigUint::from(3u32));
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SpotOrderPriceLimitation {
    /// Orderbook biding price rate cap
    pub bid_price_rate_cap: BigUint,
    /// Orderbook asking price rate floor
    pub ask_price_rate_floor: BigUint,
    /// Price rate decimal
    pub rate_decimal: u8,
}

/// Market trading settings
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct SpotMarketTradingSettings {
    /// Price max decimal
    /// Orderbook price decimal & swap price decimal use this value
    pub price_max_decimal: u8,

    /// Volume max decimal
    /// Orderbook volume decimal & swap volume decimal use this value
    /// Note: volume means base asset quantity
    pub volume_max_decimal: u8,

    /// Min order amount
    /// Orderbook min order amount & swap min order amount use this value
    /// Note: amount means quota asset quantity
    pub min_order_amount: AssetAmount,

    /// Min order volume
    /// Orderbook min order volume & swap min order volume use this value
    /// Note: volume means base asset quantity
    pub min_order_volume: AssetAmount,

    /// Price limitation
    pub price_limitation: SpotOrderPriceLimitation,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotMarketTradingFee {
    /// Orderbook taker fee
    /// Swap fee is the same as orderbook taker fee
    pub taker_fee: Nat,

    /// Orderbook maker fee
    pub maker_fee: Nat,

    /// AMM V2 fee taking ratio
    /// # Range
    /// 0 ~ 100
    /// # Example
    /// * 0: 0%
    /// * 100: 100%
    /// # Note
    /// This value is used for AMM V2
    pub amm_v2_fee_taking_ratio: Nat,

    /// Fee decimal for
    /// * `taker_fee` & `maker_fee` & `amm_v2_fee_taking_ratio`
    pub fee_decimal: u8,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotOrderPriceLimitation {
    /// Orderbook biding price rate cap
    pub bid_price_rate_cap: Nat,
    /// Orderbook asking price rate floor
    pub ask_price_rate_floor: Nat,
    /// Price rate decimal
    pub rate_decimal: u8,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotMarketTradingSettings {
    /// Price max decimal
    /// Orderbook price decimal & swap price decimal use this value
    pub price_max_decimal: u8,

    /// Volume max decimal
    /// Orderbook volume decimal & swap volume decimal use this value
    /// Note: volume means base asset quantity
    pub volume_max_decimal: u8,

    /// Min order amount
    /// Orderbook min order amount & swap min order amount use this value
    /// Note: amount means quota asset quantity
    pub min_order_amount: CandidAssetAmount,

    /// Min order volume
    /// Orderbook min order volume & swap min order volume use this value
    /// Note: volume means base asset quantity
    pub min_order_volume: CandidAssetAmount,

    /// Price limitation
    pub price_limitation: CandidSpotOrderPriceLimitation,
}

#[derive(CandidType, Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct CandidSpotMarket {
    /// Market id
    pub id: CandidMarketId,

    /// Base asset id
    pub base_asset_id: CandidAssetId,

    /// Quote asset id
    pub quote_asset_id: CandidAssetId,

    /// Market trading settings
    pub trading_settings: CandidSpotMarketTradingSettings,

    /// Market trading fee
    pub fee: CandidSpotMarketTradingFee,

    /// Market fee to
    /// Trading fee to
    pub fee_to: CandidWalletRegisterId,
}

impl From<CandidSpotMarketTradingFee> for SpotMarketTradingFee {
    fn from(candid_market_trading_fee: CandidSpotMarketTradingFee) -> Self {
        SpotMarketTradingFee {
            taker_fee: candid_market_trading_fee.taker_fee.0,
            maker_fee: candid_market_trading_fee.maker_fee.0,
            amm_v2_fee_taking_ratio: candid_market_trading_fee.amm_v2_fee_taking_ratio.0,
            fee_decimal: candid_market_trading_fee.fee_decimal,
        }
    }
}

impl From<SpotMarketTradingFee> for CandidSpotMarketTradingFee {
    fn from(market_trading_fee: SpotMarketTradingFee) -> Self {
        CandidSpotMarketTradingFee {
            taker_fee: Nat(market_trading_fee.taker_fee),
            maker_fee: Nat(market_trading_fee.maker_fee),
            amm_v2_fee_taking_ratio: Nat(market_trading_fee.amm_v2_fee_taking_ratio),
            fee_decimal: market_trading_fee.fee_decimal,
        }
    }
}

impl From<CandidSpotOrderPriceLimitation> for SpotOrderPriceLimitation {
    fn from(candid_order_price_limitation: CandidSpotOrderPriceLimitation) -> Self {
        SpotOrderPriceLimitation {
            bid_price_rate_cap: candid_order_price_limitation.bid_price_rate_cap.0,
            ask_price_rate_floor: candid_order_price_limitation.ask_price_rate_floor.0,
            rate_decimal: candid_order_price_limitation.rate_decimal,
        }
    }
}

impl From<SpotOrderPriceLimitation> for CandidSpotOrderPriceLimitation {
    fn from(order_price_limitation: SpotOrderPriceLimitation) -> Self {
        CandidSpotOrderPriceLimitation {
            bid_price_rate_cap: Nat(order_price_limitation.bid_price_rate_cap),
            ask_price_rate_floor: Nat(order_price_limitation.ask_price_rate_floor),
            rate_decimal: order_price_limitation.rate_decimal,
        }
    }
}

impl From<CandidSpotMarketTradingSettings> for SpotMarketTradingSettings {
    fn from(candid_market_trading_settings: CandidSpotMarketTradingSettings) -> Self {
        SpotMarketTradingSettings {
            price_max_decimal: candid_market_trading_settings.price_max_decimal,
            volume_max_decimal: candid_market_trading_settings.volume_max_decimal,
            min_order_amount: candid_market_trading_settings.min_order_amount.0,
            min_order_volume: candid_market_trading_settings.min_order_volume.0,
            price_limitation: candid_market_trading_settings.price_limitation.into(),
        }
    }
}

impl From<SpotMarketTradingSettings> for CandidSpotMarketTradingSettings {
    fn from(market_trading_settings: SpotMarketTradingSettings) -> Self {
        CandidSpotMarketTradingSettings {
            price_max_decimal: market_trading_settings.price_max_decimal,
            volume_max_decimal: market_trading_settings.volume_max_decimal,
            min_order_amount: market_trading_settings.min_order_amount.into(),
            min_order_volume: market_trading_settings.min_order_volume.into(),
            price_limitation: market_trading_settings.price_limitation.into(),
        }
    }
}

impl From<CandidSpotMarket> for SpotMarket {
    fn from(candid_market: CandidSpotMarket) -> Self {
        SpotMarket {
            id: candid_market.id.0,
            base_asset_id: candid_market.base_asset_id.0,
            quote_asset_id: candid_market.quote_asset_id.0,
            trading_settings: candid_market.trading_settings.into(),
            fee: candid_market.fee.into(),
            fee_to: candid_market.fee_to.0,
        }
    }
}

impl From<SpotMarket> for CandidSpotMarket {
    fn from(market: SpotMarket) -> Self {
        CandidSpotMarket {
            id: market.id.into(),
            base_asset_id: market.base_asset_id.into(),
            quote_asset_id: market.quote_asset_id.into(),
            trading_settings: market.trading_settings.into(),
            fee: market.fee.into(),
            fee_to: market.fee_to.into(),
        }
    }
}
