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


class abantether(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(abantether, self).describe(), {
            'id': 'abantether',
            'name': 'Aban tether',
            '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/abantether/64x64.png',
                'api': {
                    'public': 'https://abantether.com',
                },
                'www': 'https://abantether.com',
                'doc': [
                    'https://abantether.com',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'management/all-coins/': 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 abantether
        https://abantether.com/management/all-coins/?format=json
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetManagementAllCoins(params)
        result = []
        quotes = ['IRT', 'USDT']
        for i in range(0, len(response)):
            base = self.safe_string(response[i], 'symbol')
            for index in range(0, len(quotes)):
                quote = quotes[index]
                response[i]['base'] = base
                response[i]['quote'] = quote
                if base == quote:
                    continue
                market = self.parse_market(response[i])
                result.append(market)
        return result

    def parse_market(self, market) -> Market:
        # {
        #     'symbol': 'USDT',
        #     'name': 'Tether',
        #     'categories': [],
        #     'tetherPrice': '1',
        #     'priceBuy': '59200.0',
        #     'priceSell': '58800.0',
        #     'persianName': '\u062a\u062a\u0631',
        #     'past24': '0',
        #     'marketVolume': '1',
        #     'id': '1',
        #     'active': True,
        #     'irtDecimalPoint': '2',
        #     'tetherDecimalPoint': '6',
        #     'amountDecimalPoint': '6',
        #     'past24volume': '767287.60530837810210936763',
        #     'operationStatus': {
        #         'buyActive': True,
        #         'sellActive': True,
        #         'withdrawalActive': True,
        #         'depositActive': True,
        #         'transferActive': True,
        #     },
        # }
        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
        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': '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_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://abantether.com/management/all-coins/?format=json
        :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.publicGetManagementAllCoins(params)
        result = {}
        quotes = ['IRT', 'USDT']
        for i in range(0, len(response)):
            base = self.safe_string(response[i], 'symbol')
            for index in range(0, len(quotes)):
                quote = quotes[index]
                if base == quote:
                    continue
                response[i]['base'] = base
                response[i]['quote'] = quote
                response[i]['symbol'] = base + quote
                ticker = self.parse_ticker(response[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://abantether.com/management/all-coins/?format=json
        :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': 'USDT',
        #     'name': 'Tether',
        #     'categories': [],
        #     'tetherPrice': '1',
        #     'priceBuy': '59200.0',
        #     'priceSell': '58800.0',
        #     'persianName': '\u062a\u062a\u0631',
        #     'past24': '0',
        #     'marketVolume': '1',
        #     'id': '1',
        #     'active': True,
        #     'irtDecimalPoint': '2',
        #     'tetherDecimalPoint': '6',
        #     'amountDecimalPoint': '6',
        #     'past24volume': '767287.60530837810210936763',
        #     'operationStatus': {
        #         'buyActive': True,
        #         'sellActive': True,
        #         'withdrawalActive': True,
        #         'depositActive': True,
        #         'transferActive': True,
        #     },
        # }
        marketType = 'otc'
        marketId = self.safe_string(ticker, 'symbol')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        last = self.safe_float(ticker, 'tetherPrice', 0)
        if ticker['quote'] == 'IRT':
            last = self.safe_float(ticker, 'priceSell', 0)
        change = self.safe_float(ticker, 'past24', 0)
        baseVolume = self.safe_float(ticker, 'past24volume', 0)
        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': None,
            '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 + '?format=json'
        headers = {'Content-Type': 'application/json', 'Cookie': '__arcsco=42f03956ded5873c087d9f052b33cbff'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
