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


class tehran_exchange(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(tehran_exchange, self).describe(), {
            'id': 'tehran_exchange',
            'name': 'Tehran Exchange',
            '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,
                '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/tehran_exchange/64x64.png',
                'api': {
                    'public': 'https://otc-api.tehran.exchange',
                },
                'www': 'https://tehran.exchange',
                'doc': [
                    'https://tehran.exchange',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'otc/v1/market/pair': 1,
                        'otc/v1/market/order/pair/price': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.0025'),
                    'taker': self.parse_number('0.0025'),
                },
            },
        })

    async def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for tehran_exchange
        https://otc-api.tehran.exchange/otc/v1/market/pair
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetOtcV1MarketPair(params)
        data = self.safe_dict(response, 'data', {})
        pairs = self.safe_list(data, 'pairs', [])
        result = []
        for i in range(0, len(pairs)):
            market = self.parse_market(pairs[i])
            result.append(market)
        return result

    def parse_market(self, market) -> Market:
        # {
        #     "id": 6054,
        #     "pair": "HBAR_USDT",
        #     "status": "TRADABLE",
        #     "tradable": True,
        #     "fiatOrder": False,
        #     "quoteName": "Tether",
        #     "baseName": "Hedera",
        #     "quoteNameFa": "تتر",
        #     "baseNameFa": "هدرا هش گراف ",
        #     "quoteImageUrl": "https://s3-dev.tehranex.com/asset/coin_icon/64/usdt.png",
        #     "baseImageUrl": "https://s3-dev.tehranex.com/asset/coin_icon/64/hbar.png",
        #     "quoteSymbol": "USDT",
        #     "baseSymbol": "HBAR",
        #     "amountPrecision": 2,
        #     "feePercentage": 0.25,
        #     "providerFeePercentage": 0.05,
        #     "maxQuoteAmount": 600000,
        #     "minBaseAmount": 0.01,
        #     "minQuoteAmount": 1,
        #     "pricePrecision": 5,
        #     "baseVirtualCurrencyId": 989,
        #     "quoteVirtualCurrencyId": 1
        # }
        id = self.safe_string(market, 'pair')
        baseId = self.safe_string(market, 'baseSymbol')
        quoteId = self.safe_string(market, 'quoteSymbol')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        status = self.safe_string(market, 'status')
        tradable = self.safe_bool(market, 'tradable', False)
        active = (status == 'TRADABLE') and tradable
        amountPrecision = self.safe_integer(market, 'amountPrecision')
        pricePrecision = self.safe_integer(market, 'pricePrecision')
        minBaseAmount = self.safe_string(market, 'minBaseAmount')
        minQuoteAmount = self.safe_string(market, 'minQuoteAmount')
        maxQuoteAmount = self.safe_string(market, 'maxQuoteAmount')
        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': amountPrecision,
                'price': pricePrecision,
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': self.parse_number(minBaseAmount),
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': self.parse_number(minQuoteAmount),
                    'max': self.parse_number(maxQuoteAmount),
                },
            },
            '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://otc-api.tehran.exchange/otc/v1/market/pair
        https://otc-api.tehran.exchange/otc/v1/market/order/pair/price
        :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.publicGetOtcV1MarketPair(params)
        data = self.safe_dict(response, 'data', {})
        pairs = self.safe_list(data, 'pairs', [])
        # filter symbols from pairs
        filteredPairs = []
        for i in range(0, len(pairs)):
            pair = pairs[i]
            pairId = self.safe_string(pair, 'pair')
            symbol = self.safe_symbol(pairId)
            if symbols.includes(symbol):
                filteredPairs.append(pair)
        result = {}
        for i in range(0, len(filteredPairs)):
            pairData = filteredPairs[i]
            pairId = self.safe_string(pairData, 'pair')
            # Fetch BUY price
            request = {
                'pair': pairId,
                'side': 'BUY',
                'basedOn': 'BASE',
                'amount': 1,
            }
            priceResponse = await self.publicGetOtcV1MarketOrderPairPrice(request)
            priceData = self.safe_dict(priceResponse, 'data', {})
            price = self.safe_float(priceData, 'price', 0)
            pairData['price'] = price
            ticker = self.parse_ticker(pairData)
            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://otc-api.tehran.exchange/otc/v1/market/pair
        :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[self.safe_symbol(symbol)]

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #     "id": 6054,
        #     "pair": "HBAR_USDT",
        #     "status": "TRADABLE",
        #     "tradable": True,
        #     "baseSymbol": "HBAR",
        #     "quoteSymbol": "USDT",
        #     ...
        #     "price": 12345,
        # }
        marketType = 'spot'
        baseSymbol = self.safe_string(ticker, 'baseSymbol')
        quoteSymbol = self.safe_string(ticker, 'quoteSymbol')
        marketId = baseSymbol + '/' + quoteSymbol
        symbol = self.safe_symbol(marketId, market, None, marketType)
        price = self.safe_float(ticker, 'price')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': None,
            'low': None,
            'bid': price,
            'bidVolume': None,
            'ask': price,
            'askVolume': None,
            'open': None,
            'close': price,
            'last': price,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': None,
            'quoteVolume': None,
            'info': ticker,
        }, market)

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        query = self.omit(params, self.extract_params(path))
        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}
