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


class bitbarg(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(bitbarg, self).describe(), {
            'id': 'bitbarg',
            'name': 'Bitbarg',
            'countries': ['IR'],
            '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': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': False,
                'fetchOrder': False,
                'fetchOrderBook': False,
                '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/bitbarg/64x64.png',
                'api': {
                    'public': 'https://api.bitbarg.com',
                },
                'www': 'https://bitbarg.com/',
                'doc': [
                    'https://bitbarg.com/',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        '/api/v1/currencies': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.001'),
                    'taker': self.parse_number('0.001'),
                },
            },
        })

    def parse_market(self, market) -> Market:
        # "id": 53,
        # "icon": "https://s3.bitbarg.com/currencies/btc.webp",
        # "tradeActive": True,
        # "faName": "بیت کوین",
        # "enName": "Bitcoin",
        # "coin": "BTC",
        # "path": "bitcoin",
        # "price": 112192,
        # "quote": "813430226.5004",
        # "percent": -5.735,
        # "decimal": 8,
        # "isFavorite": False,
        baseId = self.safe_string(market, 'coin')
        quoteId = 'USDT'
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        id = baseId + '/' + quoteId
        return {
            'id': id,
            'symbol': id,
            '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,
        }

    def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for bitbarg
        https://api.bitbarg.com/api/v1/currencies?pageSize=-1
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        request = {
            'pageSize': -1,
        }
        response = self.publicGetApiV1Currencies(self.extend(request, params))
        result = []
        data = self.safe_dict(response, 'result', {})
        items = self.safe_list(data, 'items', [])
        # Create markets for each currency with IRT quote
        for i in range(0, len(items)):
            market = self.parse_market(items[i])
            result.append(market)
        return result

    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.bitbarg.com/api/v1/currencies?pageSize=-1
        :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>`
        """
        self.load_markets()
        if symbols is not None:
            symbols = self.market_symbols(symbols)
        request = {
            'pageSize': -1,
        }
        response = self.publicGetApiV1Currencies(request)
        data = self.safe_dict(response, 'result', {})
        items = self.safe_list(data, 'items', [])
        result = {}
        for i in range(0, len(items)):
            coinData = items[i]
            baseId = self.safe_string(coinData, 'coin')
            # Create ticker for USDT quote
            quoteId = 'USDT'
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            symbol = base + '/' + quote
            ticker = self.extend({
                'symbol': symbol,
                'baseId': baseId,
                'quoteId': quoteId,
                'id': baseId + '/' + quoteId,
            }, coinData)
            result[symbol] = self.parse_ticker(ticker)
        return self.filter_by_array_tickers(result, 'symbol', symbols)

    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.bitbarg.com/api/v1/currencies?pageSize=-1
        :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 = self.fetch_tickers([symbol])
        return ticker[symbol]

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #     "id": 1,
        #     "icon": "https://...",
        #     "tradeActive": True,
        #     "faName": "بیت کوین",
        #     "enName": "Bitcoin",
        #     "coin": "BTC",
        #     "path": "bitcoin",
        #     "price": 110387.56,
        #     "quote": "57479298399.76",
        #     "percent": -3.01,
        #     "decimal": 5,
        #     "isFavorite": False,
        #     "chart": [...]
        # }
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'coin') + '/' + 'USDT'
        symbol = self.safe_symbol(marketId, market, None, marketType)
        last = self.safe_float(ticker, 'price', 0)
        percentage = self.safe_float(ticker, 'percent', 0)
        baseVolume = self.safe_float(ticker, 'quote')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': None,
            'low': None,
            'bid': last,
            'bidVolume': None,
            'ask': last,
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': None,
            'info': ticker,
        }, market)

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