# -*- 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.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': 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,
                '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/abantether/64x64.png',
                'api': {
                    'public': 'https://api.abantether.com',
                },
                'www': 'https://abantether.com',
                'doc': [
                    'https://abantether.com',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'manager/coins/data': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.001'),
                    'taker': self.parse_number('0.001'),
                },
            },
        })

    async def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for abantether
        https://api.abantether.com/manager/coins/data
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetManagerCoinsData(params)
        data = self.safe_list(response, 'data', [])
        result = []
        quotes = ['IRT', 'USDT']
        for i in range(0, len(data)):
            base = self.safe_string(data[i], 'symbol')
            for index in range(0, len(quotes)):
                quote = quotes[index]
                data[i]['base'] = base
                data[i]['quote'] = quote
                if base == quote:
                    continue
                market = self.parse_market(data[i])
                result.append(market)
        return result

    def parse_market(self, market) -> Market:
        # {
        #     "id": 1,
        #     "name": "Tether USDt",
        #     "symbol": "USDT",
        #     "persian_name": "تتر",
        #     "is_active": True,
        #     "is_withdrawal_active": True,
        #     "is_deposit_active": True,
        #     "is_mid_wallet_transfer_active": True,
        #     "is_buy_active": True,
        #     "is_sell_active": True,
        #     "is_credit_active": True,
        #     "min_trade": "1.00",
        #     "max_trade": "100000.00",
        #     "tether_price": "1",
        #     "price_buy": "113540.0",
        #     "price_sell": "112630.0",
        #     "volume24h": "225163179366.25",
        #     "percent_change_1h": "0.00",
        #     "percent_change_24h": "0.00",
        #     "percent_change_7d": "0.04",
        #     "market_cap": "179884960573.99",
        #     "coin_type": "COIN",
        #     "exchange_type": "fake",
        #     "icon": "f71021586005413ea6f3a0bd1f7d8a55",
        #     "fund_tether_buy": "0",
        #     "fund_tether_sell": "0",
        #     "irt_decimal_point": 2,
        #     "tether_decimal_point": 6,
        #     "amount_decimal_point": 6,
        #     "base": "BTC",
        #     "qoute": "USDT",
        # },
        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': '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,
        }

    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://api.abantether.com/manager/coins/data
        :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.publicGetManagerCoinsData(params)
        data = self.safe_list(response, 'data', [])
        result = {}
        quotes = ['IRT', 'USDT']
        for i in range(0, len(data)):
            base = self.safe_string(data[i], 'symbol')
            for index in range(0, len(quotes)):
                quote = quotes[index]
                if base == quote:
                    continue
                data[i]['base'] = base
                data[i]['quote'] = quote
                data[i]['symbol'] = base + quote
                ticker = self.parse_ticker(data[i])
                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://api.abantether.com/manager/coins/data
        :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[symbol]

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #     "id": 2,
        #     "name": "Bitcoin",
        #     "symbol": "BTC",
        #     "persian_name": "بیت کوین",
        #     "is_active": True,
        #     "is_withdrawal_active": True,
        #     "is_deposit_active": True,
        #     "is_mid_wallet_transfer_active": True,
        #     "is_buy_active": True,
        #     "is_sell_active": True,
        #     "is_credit_active": True,
        #     "min_trade": "1.00",
        #     "max_trade": "65000.00",
        #     "tether_price": "114909.43000000",
        #     "price_buy": "13049114870.800000000",
        #     "price_sell": "12944547289.500000000",
        #     "volume24h": "93585526493.26",
        #     "percent_change_1h": "-0.29",
        #     "percent_change_24h": "3.22",
        #     "percent_change_7d": "-7.19",
        #     "market_cap": "2292874615411.72",
        #     "coin_type": "COIN",
        #     "exchange_type": "binance",
        #     "icon": "561aa10abc0c45f7aa4499f48d618c80",
        #     "fund_tether_buy": "0",
        #     "fund_tether_sell": "0",
        #     "irt_decimal_point": 0,
        #     "tether_decimal_point": 2,
        #     "amount_decimal_point": 9
        # },
        marketType = 'otc'
        marketId = self.safe_string(ticker, 'symbol')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        last = self.safe_float(ticker, 'tether_price', 0)
        if ticker['quote'] == 'IRT':
            last = self.safe_float(ticker, 'price_buy', 0)
        change = self.safe_float(ticker, 'percent_change_24h', 0)
        baseVolume = self.safe_float(ticker, 'volume24h', 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}
