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


class iranexchange(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(iranexchange, self).describe(), {
            'id': 'iranexchange',
            'name': 'Iran Exchange',
            'countries': ['IR'],
            'rateLimit': 1000,
            'version': '1',
            'certified': False,
            'pro': False,
            'timeout': 30000,  # milliseconds = seconds * 1000
            'has': {
                'CORS': None,
                'spot': False,
                '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,
                '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/iran-exchange/64x64.png',
                'api': {
                    'public': 'https://api.iranexchange.com/api/public/modules/crypto',
                },
                'www': 'https://iranexchange.com/',
                'doc': [
                    'https://iranexchange.com/',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'v1/client/listProduct': 1,
                        'v1/client/getBySymbol': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.001'),
                    'taker': self.parse_number('0.001'),
                },
            },
        })

    def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for iranexchange
        https://iranexchange.co/
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetV1ClientListProduct()
        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: "60b08a57b202353abb592032",
        # name: "Bitcoin",
        # fa_name: "بیت کوین",
        # symbol: "BTC",
        # slug: "bitcoin",
        # is_sell_to_customer_active: 1,
        # is_fast_sell_to_customer_active: 1,
        # is_buy_from_customer_active: 1,
        # logo: "https://iranexchange.com/strapi/media/BTC_78d99b9d12.png",
        # dollar_price: 89240.18,
        # sell_to_iranicard_currency_price: 1234526,
        # buy_from_iranicard_currency_price: 1239474,
        # fast_sell_to_iranicard_currency_price: 1234526,
        # buy_from_iranicard_network_list: [
        # {
        # network: "BTC",
        # name: "Bitcoin",
        # addressRegex: "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^[(bc1q)|(bc1p)][0-9A-Za-z]{37,62}$",
        # coin: "BTC",
        # withdrawEnable: True,
        # depositEnable: True,
        # withdrawMin: "0.000100000",
        # withdrawMax: null,
        # withdrawFee: "0.000100000",
        # sameAddress: False,
        # memoRegex: null,
        # tradeEnable: True
        # }
        # ],
        # sell_to_iranicard_network_list: [
        # {
        # network: "BTC",
        # name: "Bitcoin",
        # addressRegex: "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^[(bc1q)|(bc1p)][0-9A-Za-z]{37,62}$",
        # coin: "BTC",
        # withdrawEnable: True,
        # depositEnable: True,
        # withdrawMin: "0.000100000",
        # withdrawMax: null,
        # withdrawFee: "0.000100000",
        # sameAddress: False,
        # memoRegex: null,
        # tradeEnable: True
        # }
        # ],
        # is_price_maker_active: 1,
        # quotation: {
        # maxPrice: "90199.99",
        # minPrice: "88925",
        # dailyChangePercent: "-0.26"
        # },
        # dailyChangePercent: -0.26,
        # order: 0,
        # stock_status: "in_stock",
        # stock_label: null,
        # stock_description: null
        # },
        id = self.safe_string(market, 'symbol') + '_' + 'IRT'
        baseId = self.safe_string(market, 'symbol')
        quoteId = 'IRT'
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        baseId = baseId.lower()
        quoteId = quoteId.lower()
        return {
            'id': id,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': None,
            'type': 'otc',
            '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_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://iranexchange.co/
        :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.publicGetV1ClientListProduct()
        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)

    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://iranexchange.co/
        :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>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'id': market['base'],
        }
        response = self.publicGetV1ClientGetBySymbol(request)
        marketData = self.safe_dict(response, 'data')
        ticker = self.parse_ticker(marketData)
        return ticker

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        # _id: "60b08a57b202353abb592032",
        # name: "Bitcoin",
        # fa_name: "بیت کوین",
        # symbol: "BTC",
        # slug: "bitcoin",
        # is_sell_to_customer_active: 1,
        # is_fast_sell_to_customer_active: 1,
        # is_buy_from_customer_active: 1,
        # logo: "https://iranexchange.com/strapi/media/BTC_78d99b9d12.png",
        # dollar_price: 89240.18,
        # sell_to_iranicard_currency_price: 1234526,
        # buy_from_iranicard_currency_price: 1239474,
        # fast_sell_to_iranicard_currency_price: 1234526,
        # buy_from_iranicard_network_list: [
        # {
        # network: "BTC",
        # name: "Bitcoin",
        # addressRegex: "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^[(bc1q)|(bc1p)][0-9A-Za-z]{37,62}$",
        # coin: "BTC",
        # withdrawEnable: True,
        # depositEnable: True,
        # withdrawMin: "0.000100000",
        # withdrawMax: null,
        # withdrawFee: "0.000100000",
        # sameAddress: False,
        # memoRegex: null,
        # tradeEnable: True
        # }
        # ],
        # sell_to_iranicard_network_list: [
        # {
        # network: "BTC",
        # name: "Bitcoin",
        # addressRegex: "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^[(bc1q)|(bc1p)][0-9A-Za-z]{37,62}$",
        # coin: "BTC",
        # withdrawEnable: True,
        # depositEnable: True,
        # withdrawMin: "0.000100000",
        # withdrawMax: null,
        # withdrawFee: "0.000100000",
        # sameAddress: False,
        # memoRegex: null,
        # tradeEnable: True
        # }
        # ],
        # is_price_maker_active: 1,
        # quotation: {
        # maxPrice: "90199.99",
        # minPrice: "88925",
        # dailyChangePercent: "-0.26"
        # },
        # dailyChangePercent: -0.26,
        # order: 0,
        # stock_status: "in_stock",
        # stock_label: null,
        # stock_description: null
        # }
        marketType = 'otc'
        marketId = self.safe_string(ticker, 'symbol') + '_' + 'IRT'
        symbol = self.safe_symbol(marketId, market, None, marketType)
        quotation = self.safe_value(ticker, 'quotation', {})
        dollar_price = self.safe_float(ticker, 'dollar_price', 0)
        high = self.safe_float(quotation, 'maxPrice', 0) * dollar_price
        low = self.safe_float(quotation, 'minPrice', 0) * dollar_price
        bid = self.safe_float(ticker, 'sell_to_iranicard_currency_price', 0) * dollar_price
        ask = self.safe_float(ticker, 'buy_from_iranicard_currency_price', 0) * dollar_price
        last = self.safe_float(ticker, 'sell_to_iranicard_currency_price', 0) * dollar_price
        change = self.safe_float(quotation, 'dailyChangePercent', 0)
        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': last,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': change,
            '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 + '?' + self.urlencode(query)
        pair_id = self.safe_string(params, 'id')
        if pair_id is not None:
            url = self.urls['api']['public'] + '/' + path + '/' + pair_id
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
