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


class cafearz(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(cafearz, self).describe(), {
            'id': 'cafearz',
            'name': 'Cafearz',
            '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,
                'otc': True,
                'setLeverage': False,
                'setMarginMode': False,
                'transfer': False,
                'withdraw': False,
            },
            'comment': 'This comment is optional',
            'urls': {
                'logo': 'https://cdn.arz.digital/cr-odin/img/exchanges/cafearz/64x64.png',
                'api': {
                    'public': 'https://api2.cafearz.com',
                },
                'www': 'https://cafearz.com/',
                'doc': [
                    'https://cafearz.com/',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        '/api/client/v1/currencies/prices/digital': 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:
        # {
        #     "symbol": "BTC",
        #     "name": "Bitcoin",
        #     "title": "بیت کوین",
        #     "service_id": 14,
        #     "rank": 1,
        #     "price": {
        #         "buy": 12726581792.3999996185302734375,
        #         "sell": 12571941095.936672210693359375,
        #         "dollar": 110387.5599999999976716935634613037109375
        #     },
        #     "chart": {
        #         "changes": "down",
        #         "changes_percentage": 107.0799999999999982946974341757595539093017578125,
        #         "data": {
        #             "1404/07/05": "109643.46000000",
        #             "1404/07/06": "109635.85000000",
        #             "1404/07/07": "112163.95000000",
        #             "1404/07/08": "114311.96000000",
        #             "1404/07/09": "114048.93000000",
        #             "1404/07/10": "118594.99000000",
        #             "1404/07/11": "120529.35000000",
        #             "1404/07/12": "122232.00000000",
        #             "1404/07/13": "122391.00000000",
        #             "1404/07/14": "123482.31000000",
        #             "1404/07/15": "124658.54000000",
        #             "1404/07/16": "121332.95000000",
        #             "1404/07/17": "123306.00000000",
        #             "1404/07/18": "121662.40000000",
        #             "1404/07/19": "113613.18000000"
        #         }
        #     },
        #     "decimal_digit": "5",
        #     "market_cap": 2018807729876.182861328125,
        #     "volume_24h": 57479298399.76000213623046875,
        #     "percent_change_1h": 0.00643466000000000003244959856374407536350190639495849609375,
        #     "percent_change_24h": -3.013435680000000171929741554777137935161590576171875,
        #     "percent_change_7d": -3.848675339999999778228811919689178466796875,
        #     "base_icon": "https://api2.cafearz.com/assets/images/coins/1.png",
        #     "icon": "https://storage.cafearz.com/wp-content/uploads/coins/BTC.png"
        # },
        baseId = self.safe_string(market, 'symbol')
        quoteId = 'IRT'
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        id = baseId + '/' + quoteId
        return {
            'id': id,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': None,
            'type': 'spot',
            'spot': False,
            '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 cafearz
        https://api2.cafearz.com/api/client/v1/currencies/prices/digital
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetApiClientV1CurrenciesPricesDigital(params)
        result = []
        prices = self.safe_dict(response, 'prices', {})
        symbols = list(prices.keys())
        # Create markets for each symbol with IRT quote
        for i in range(0, len(symbols)):
            market = self.parse_market(prices[symbols[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://api2.cafearz.com/api/client/v1/currencies/prices/digital
        :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)
        response = self.publicGetApiClientV1CurrenciesPricesDigital(params)
        prices = self.safe_dict(response, 'prices', {})
        result = {}
        coinSymbols = list(prices.keys())
        for i in range(0, len(coinSymbols)):
            baseId = coinSymbols[i]
            coinData = prices[baseId]
            # Create ticker for IRT quote
            quoteId = 'IRT'
            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://api2.cafearz.com/api/client/v1/currencies/prices/digital
        :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:
        # {
        #     "symbol": "BTC",
        #     "name": "Bitcoin",
        #     "title": "بیت کوین",
        #     "service_id": 14,
        #     "rank": 1,
        #     "price": {
        #         "buy": 13462469875.799999,
        #         "sell": 13298881860,
        #         "dollar": 117689.22
        #     },
        #     "chart": {
        #         "changes": "down",
        #         "changes_percentage": 101.33,
        #         "data": {...}
        #     },
        #     "decimal_digit": "5",
        #     "market_cap": 2018807729876.182861,
        #     "volume_24h": 57479298399.76,
        #     "percent_change_1h": 0.00643466,
        #     "percent_change_24h": -3.013435,
        #     "percent_change_7d": -3.848675,
        #     "base_icon": "...",
        #     "icon": "..."
        # }
        marketType = 'otc'
        marketId = self.safe_string(ticker, 'id')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        priceData = self.safe_dict(ticker, 'price', {})
        last = self.safe_float(priceData, 'buy', 0)
        bid = self.safe_float(priceData, 'sell', 0)
        ask = self.safe_float(priceData, 'buy', 0)
        percentage = self.safe_float(ticker, 'percent_change_24h', 0)
        baseVolume = self.safe_float(ticker, 'volume_24h')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': None,
            'low': None,
            'bid': bid,
            'bidVolume': None,
            'ask': ask,
            '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
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
