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


class tetherland(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(tetherland, self).describe(), {
            'id': 'tetherland',
            'name': 'TetherLand',
            '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/tetherland/64x64.png',
                'api': {
                    'public': 'https://service.tetherland.com',
                },
                'www': 'https://tetherland.org',
                'doc': [
                    'https://docs.tetherland.com/docs/tetherland/71ca11f41704f-user-api',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'api/v5/currencies': 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 tetherland
        https://docs.tetherland.com/docs/tetherland/71ca11f41704f-user-api
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetApiV5Currencies(params)
        markets = self.safe_list(response, 'data')
        result = []
        quotes = ['USDT', 'IRT']
        for i in range(0, len(markets)):
            for key in range(0, len(quotes)):
                if markets[i]['symbol'] == 'USDT' and quotes[key] == 'USDT':
                    continue
                markets[i]['quote'] = quotes[key]
                market = self.parse_market(markets[i])
                result.append(market)
        return result

    def parse_market(self, market) -> Market:
        # {
        #     'name': 'Bitcoin',
        #     'fa_name': 'بیت کوین',
        #     'logo': '/uploads/images/2022/8/masc3iMjEPBTC.svg',
        #     'accent_color': '#ff8d00',
        #     'symbol': 'BTC',
        #     'price': '69,497.50',
        #     'toman_amount': 4117726875,
        #     'min_usdt_value': null,
        #     'min_usdt_amount': 15,
        #     'max_usdt_amount': 10000,
        #     'min_value': null,
        #     'max_amount': '0.200000000000',
        #     'min_irr_amount': 883500,
        #     'max_irr_amount': 589000000,
        #     'priority': 1,
        #     'price_round_digit': 2,
        #     'amount_round_digit': 6,
        #     'changes_24h': -2.68,
        #     'changes_7d': 7.522256527082521,
        #     'trendy': 0,
        #     'exchange': null,
        #     'categories': [],
        #     'createdAt': null,
        #     'has_staking': True,
        #     'staking_plan': {
        #         'id': 38,
        #         'coin_id': 1,
        #         'periods': {'30': '1.2', '60': '1.5', 'flex': '1'},
        #         'capacity': '5.00000',
        #         'minimum_staking_amount': '0.00150',
        #         'maximum_staking_amount': '1.00000',
        #         'total_staked': '5.00000',
        #         'largest_benefit': 1.5,
        #         'trendy': 0,
        #         'status': 'COMPLETED',
        #         'info': 'رمزارز مورد نظر PoS نیست و پاداش حاصل از نگه‌داری آن از طریق دیفای استیکینگ تامین می‌شود.',
        #         'created_at': '2023-07-15T13:01:25.000000Z',
        #         'updated_at': '2024-06-01T14:56:40.000000Z',
        #         'deleted_at': null,
        #         'priority': 18,
        #     },
        # }
        baseId, quoteId = [self.safe_string(market, 'symbol'), 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,
        }

    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://docs.tetherland.com/docs/tetherland/71ca11f41704f-user-api
        :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.publicGetApiV5Currencies(params)
        markets = self.safe_list(response, 'data')
        result = {}
        quotes = ['USDT', 'IRT']
        for i in range(0, len(markets)):
            for key in range(0, len(quotes)):
                if markets[i]['symbol'] == 'USDT' and quotes[key] == 'USDT':
                    continue
                markets[i]['quote'] = quotes[key]
                markets[i]['id'] = markets[i]['symbol'] + '/' + markets[i]['quote']
                market = self.parse_ticker(markets[i])
                symbol = market['symbol']
                result[symbol] = market
        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://docs.tetherland.com/docs/tetherland/71ca11f41704f-user-api
        :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:
        # {
        #     'name': 'Bitcoin',
        #     'fa_name': 'بیت کوین',
        #     'logo': '/uploads/images/2022/8/masc3iMjEPBTC.svg',
        #     'accent_color': '#ff8d00',
        #     'symbol': 'BTC',
        #     'price': '69,497.50',
        #     'toman_amount': 4117726875,
        #     'min_usdt_value': null,
        #     'min_usdt_amount': 15,
        #     'max_usdt_amount': 10000,
        #     'min_value': null,
        #     'max_amount': '0.200000000000',
        #     'min_irr_amount': 883500,
        #     'max_irr_amount': 589000000,
        #     'priority': 1,
        #     'price_round_digit': 2,
        #     'amount_round_digit': 6,
        #     'changes_24h': -2.68,
        #     'changes_7d': 7.522256527082521,
        #     'trendy': 0,
        #     'exchange': null,
        #     'categories': [],
        #     'createdAt': null,
        #     'has_staking': True,
        #     'staking_plan': {
        #         'id': 38,
        #         'coin_id': 1,
        #         'periods': {'30': '1.2', '60': '1.5', 'flex': '1'},
        #         'capacity': '5.00000',
        #         'minimum_staking_amount': '0.00150',
        #         'maximum_staking_amount': '1.00000',
        #         'total_staked': '5.00000',
        #         'largest_benefit': 1.5,
        #         'trendy': 0,
        #         'status': 'COMPLETED',
        #         'info': 'رمزارز مورد نظر PoS نیست و پاداش حاصل از نگه‌داری آن از طریق دیفای استیکینگ تامین می‌شود.',
        #         'created_at': '2023-07-15T13:01:25.000000Z',
        #         'updated_at': '2024-06-01T14:56:40.000000Z',
        #         'deleted_at': null,
        #         'priority': 18,
        #     },
        # }
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'id')
        quote = self.safe_string(ticker, 'quote')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        last = float(self.safe_string(ticker, 'price', '').replace(',', ''))
        if quote == 'IRT':
            last = self.safe_float(ticker, 'toman_amount', 0)
        change = self.safe_float(ticker, 'changes_24h', 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': None,
            '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}
