# -*- 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.bitunix import ImplicitAPI
from ccxt.base.types import Any, Market, Strings, Ticker, Tickers
from typing import List


class bitunix(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(bitunix, self).describe(), {
            'id': 'bitunix',
            'name': 'bitunix',
            'countries': ['IR'],
            'rateLimit': 1000,
            'version': '1',
            'certified': False,
            'pro': False,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': True,
                '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/bitunix/64x64.png',
                'api': {
                    'market': 'https://openapi.bitunix.com/',
                    'tickers': 'https://api.bitunix.com/',
                },
                'www': 'https://www.bitunix.com/',
                'doc': [
                    'https://openapidoc.bitunix.com/',
                ],
            },
            'timeframes': {
                '1m': '1',
                '5m': '5',
                '15m': '15',
                '30m': '30',
                '1h': '60',
                '3h': '180',
                '4h': '240',
                '12h': '720',
                '1d': '1D',
                '1w': '1W',
            },
            'api': {
                'public': {
                    'get': {
                        'api/spot/v1/common/coin_pair/list/': 1,
                        'web/api/v1/common/tickers/': 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 bitunix
        https://api-docs.bitunix.ir/#be8d9c51a2
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetApiSpotV1CommonCoinPairList(params)
        markets = self.safe_list(response, 'data')
        result = []
        for i in range(0, len(markets)):
            market = self.parse_market(markets[i])
            result.append(market)
        return result

    def parse_market(self, market) -> Market:
        #       {
        # id: 1,
        # symbol: "btcusdt",
        # base: "BTC",
        # baseIcon: "https://img.bitunix.com/config/kv/228408.png",
        # quote: "USDT",
        # quoteIcon: "https://img.bitunix.com/config/coin/USDT.png",
        # basePrecision: 5,
        # quotePrecision: 2,
        # minPrice: "10.0000000000000000",
        # minVolume: "0.0000500000000000",
        # maxAmount: "500000.0000000000000000",
        # minAmount: "0.0000000000000000",
        # maxLimitOrderAmount: "1500000.0000000000000000",
        # maxMarketOrderAmount: "2000000.0000000000000000",
        # maxSlippage: "0.0500",
        # premiumFactor: "0.0500",
        # minBuyPriceOffset: "-0.8000",
        # maxSellPriceOffset: "50.0000",
        # isOpen: 1,
        # isHot: 1,
        # isRecommend: 1,
        # isShow: 1,
        # tradeArea: "USDT",
        # sort: 1,
        # openTime: null,
        # ctime: "2023-05-12T18:03:08Z",
        # precisions: [
        # "0.0100000000000000",
        # "0.1000000000000000",
        # "1.0000000000000000",
        # "10.0000000000000000",
        # "100.0000000000000000"
        # ]
        # }
        baseId = self.safe_string(market, 'base')
        quoteId = self.safe_string(market, 'quote')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        id = (base + quote)
        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': True,
            'contract': False,
            'linear': None,
            'inverse': None,
            'contractSize': None,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': None,
                'price': None,
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': None,
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': None,
                    '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://api-docs.bitunix.ir/#be8d9c51a2
        :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)
        response = await self.publicGetWebApiV1CommonTickers()
        markets = self.safe_list(response, 'data')
        result = {}
        for i in range(0, len(markets)):
            ticker = self.parse_ticker(markets[i])
            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://api-docs.bitunix.ir/#be8d9c51a2
        :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>`
        """
        ticker = await self.fetch_tickers([symbol])
        return ticker[symbol]

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        #        {
        # symbol: "BTCUSDT",
        # base: "BTC",
        # quote: "USDT",
        # close: "112832.34",
        # rose24h: "0.2276416293",
        # volume: "228310106.7861019"
        # },
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'symbol')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        last = self.safe_float(ticker, 'close', 0)
        change = self.safe_float(ticker, 'rose24h', 0)
        quoteVolume = self.safe_float(ticker, 'volume', 0)
        baseVolume = 0
        if last != 0:
            baseVolume = quoteVolume / last
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': None,
            'low': None,
            'bid': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': change,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api']['market'] + '/' + path
        if path == 'web/api/v1/common/tickers/':
            url = self.urls['api']['tickers'] + '/' + path
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
