# -*- coding: utf-8 -*-

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

from ccxt.async_support.base.exchange import Exchange
from ccxt.abstract.bydfi import ImplicitAPI
from ccxt.base.types import Any, Int, Market, OrderBook, Strings, Ticker, Tickers
from typing import List


class bydfi(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(bydfi, self).describe(), {
            'id': 'bydfi',
            'name': 'Bydfi',
            'countries': ['SC'],  # Seychelles
            'rateLimit': 1000,
            'version': '1',
            'certified': False,
            'pro': False,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelAllOrders': False,
                'cancelOrder': False,
                'cancelOrders': False,
                'createDepositAddress': False,
                'createOrder': False,
                'createStopLimitOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'editOrder': False,
                'fetchBalance': False,
                'fetchBorrowInterest': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchClosedOrders': False,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': False,
                'fetchDepositAddress': False,
                'fetchDeposits': False,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchL2OrderBook': False,
                'fetchL3OrderBook': False,
                'fetchLedger': False,
                'fetchLedgerEntry': False,
                'fetchLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': False,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': False,
                'fetchOrder': False,
                'fetchOrderBook': True,
                'fetchOrders': False,
                'fetchOrderTrades': 'emulated',
                'fetchPositions': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': False,
                'fetchTrades': False,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchWithdrawals': False,
                'setLeverage': False,
                'setMarginMode': False,
                'transfer': False,
                'withdraw': False,
            },
            'comment': 'This comment is optional',
            'urls': {
                'logo': 'https://cdn.arz.digital/cr-odin/img/exchanges/bydfi/64x64.png',
                'api': {
                    'public': 'https://www.bydfi.com',
                    'quote': 'https://quote.bydfi.pro',
                },
                'www': 'https://www.bydfi.com/',
                'doc': [
                    'https://www.bydfi.com/',
                ],
            },
            'timeframes': {
                '1m': '1',
                '5m': '5',
                '15m': '15',
                '30m': '30',
                '1h': '60',
                '4h': '240',
                '1d': 'D',
                '1w': 'W',
                '1M': 'M',
            },
            'api': {
                'public': {
                    'get': {
                        'api/spot/product/list': 1,
                        'api/tv/tradingView/history': 1,
                    },
                },
                'quote': {
                    'get': {
                        'tickers': 1,
                        'mkpai/depth-v2': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.001'),
                    'taker': self.parse_number('0.001'),
                },
            },
        })

    async def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for bydfi
        https://www.bydfi.com/api/spot/product/list
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetApiSpotProductList(params)
        data = self.safe_list(response, 'data', [])
        result = []
        for i in range(0, len(data)):
            market = self.parse_market(data[i])
            result.append(market)
        return result

    def parse_market(self, market) -> Market:
        # {
        #     "symbol": "BTC_USDT",
        #     "alias": "BTC/USDT",
        #     "baseCoin": "BTC",
        #     "quoteCoin": "USDT",
        #     "icon": "https://...",
        #     "type": 1,
        #     "tags": "hot",
        #     "visible": True,
        #     "anonymous": False,
        #     "canBuy": True,
        #     "canSell": True,
        #     "canGrid": True,
        #     "depth": "0.01,0.1,1",
        #     "matchMode": 1,
        #     "priceScale": 2,
        #     "volumeScale": 6,
        #     "amountScale": 2,
        #     "makerRate": 0.001,
        #     "takerRate": 0.001,
        #     "feeCoin": "USDT",
        #     "volumeMin": 0.000001,
        #     "amountMin": 5
        # }
        id = self.safe_string(market, 'symbol')
        baseId = self.safe_string(market, 'baseCoin')
        quoteId = self.safe_string(market, 'quoteCoin')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        visible = self.safe_bool(market, 'visible', True)
        canBuy = self.safe_bool(market, 'canBuy', True)
        canSell = self.safe_bool(market, 'canSell', True)
        active = visible and canBuy and canSell
        return {
            'id': id,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': None,
            'type': 'spot',
            'spot': True,
            'margin': False,
            'swap': False,
            'future': False,
            'option': False,
            'active': active,
            'contract': False,
            'linear': None,
            'inverse': None,
            'contractSize': None,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.safe_integer(market, 'volumeScale'),
                'price': self.safe_integer(market, 'priceScale'),
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.safe_number(market, 'volumeMin'),
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': self.safe_number(market, 'amountMin'),
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        }

    async def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        https://quote.bydfi.pro/tickers?preHour=24
        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        if symbols is not None:
            symbols = self.market_symbols(symbols)
        request = {
            'preHour': 24,
        }
        response = await self.quoteGetTickers(self.extend(request, params))
        data = self.safe_string(response, 'data', '')
        # Parse the CSV-like response(cast to string for safety)
        tickers = str(data).split(';')
        result = {}
        for i in range(0, len(tickers)):
            tickerStr = tickers[i].strip()
            if len(tickerStr) == 0:
                continue
            ticker = self.parse_ticker(tickerStr)
            symbol = ticker['symbol']
            result[symbol] = ticker
        return self.filter_by_array_tickers(result, 'symbol', symbols)

    async def fetch_ticker(self, symbol: str, params={}) -> Ticker:
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        https://quote.bydfi.pro/tickers?preHour=24
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        tickers = await self.fetch_tickers([symbol], params)
        return tickers[symbol]

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # BTC_USDT, -1, 112148.56000, 121452.59000, 0.00000, 0.00000, 0.00000, 0.0000, 122518.22000, 102403.50000, 2935.7203
        # Fields:
        # 0: symbol(BTC_USDT)
        # 1: trend indicator(-1 = down, 0 = neutral, 1 = up)
        # 2: last price
        # 3: 24h high
        # 4: 24h low
        # 5: price change
        # 6: base volume(BTC)
        # 7: price change percentage
        # 8: bid price
        # 9: ask price
        # 10: 24h quote volume(USDT)
        parts = []
        if isinstance(ticker, str):
            parts = ticker.split(',')
        else:
            return self.safe_ticker({}, market)
        if len(parts) < 11:
            return self.safe_ticker({}, market)
        marketType = 'spot'
        marketId = parts[0].strip()
        symbol = self.safe_symbol(marketId, market, '_', marketType)
        last = self.safe_float(parts, 2)
        high = self.safe_float(parts, 3)
        low = self.safe_float(parts, 4)
        change = self.safe_float(parts, 5)
        baseVolume = self.safe_float(parts, 6)
        percentage = self.safe_float(parts, 7)
        bid = self.safe_float(parts, 8)
        ask = self.safe_float(parts, 9)
        quoteVolume = self.safe_float(parts, 10)
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': high,
            'low': low,
            'bid': bid,
            'bidVolume': None,
            'ask': ask,
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    async def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        https://www.bydfi.com/api/tv/tradingView/history
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        endTime = Date.now()
        request = {
            'symbol': market['id'],
            'from': (endTime / 1000) - (24 * 60 * 60),
            'to': endTime / 1000,
            'resolution': self.safe_string(self.timeframes, timeframe, timeframe),
        }
        if since is not None:
            request['from'] = since / 1000
        request['from'] = self.safe_integer(request, 'from')
        request['to'] = self.safe_integer(request, 'to')
        if timeframe is not None:
            request['resolution'] = self.safe_string(self.timeframes, timeframe, timeframe)
        response = await self.publicGetApiTvTradingViewHistory(request)
        openList = self.safe_list(response, 'o', [])
        highList = self.safe_list(response, 'h', [])
        lowList = self.safe_list(response, 'l', [])
        closeList = self.safe_list(response, 'c', [])
        volumeList = self.safe_list(response, 'v', [])
        timestampList = self.safe_list(response, 't', [])
        ohlcvs = []
        for i in range(0, len(openList)):
            ohlcvs.append([
                self.safe_integer(timestampList, i),
                self.safe_float(openList, i),
                self.safe_float(highList, i),
                self.safe_float(lowList, i),
                self.safe_float(closeList, i),
                self.safe_float(volumeList, i),
            ])
        return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)

    async def fetch_order_book(self, symbol: str, limit: Int = 1, params={}) -> OrderBook:
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        https://quote.bydfi.pro/mkpai/depth-v2
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'businessType': market['id'],
            'dType': 0,
        }
        if limit is not None:
            request['size'] = limit
        response = await self.quoteGetMkpaiDepthV2(request)
        data = self.safe_dict(response, 'data', {})
        timestamp = Date.now()
        orderbook = self.parse_order_book(data, symbol, timestamp, 'bids', 'asks', 'price', 'amount')
        return orderbook

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        query = self.omit(params, self.extract_params(path))
        url = ''
        if api == 'quote':
            url = self.urls['api']['quote'] + '/' + path
        else:
            url = self.urls['api']['public'] + '/' + path
        if query:
            url += '?' + self.urlencode(query)
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
