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


class pingi(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(pingi, self).describe(), {
            'id': 'pingi',
            'name': 'Pingi',
            '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': True,
                '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': 'Pingi SPOT Exchange',
            'urls': {
                'logo': 'https://cdn.arz.digital/cr-odin/img/exchanges/pingi/64x64.png',
                'api': {
                    'public': 'https://api5.pingi.co/trading',
                },
                'www': 'https://pingi.co',
                'doc': [
                    'https://pingi.co',
                ],
            },
            'timeframes': {
                '1m': '1',
                '5m': '5',
                '15m': '15',
                '30m': '30',
                '1h': '60',
                '4h': '240',
                '1d': '1D',
                '1w': '1W',
            },
            'api': {
                'public': {
                    'get': {
                        'market/prices': 1,
                        'udf/history': 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 pingi
        https://api5.pingi.co/trading/market/prices/
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetMarketPrices(params)
        # Response structure:
        # {
        #   "statusCode": 200,
        #   "ok": True,
        #   "data": {
        #     "ETH_USDT": {
        #       "market": "ETH_USDT",
        #       "marketId": 6,
        #       "marketVolume": "128889.02937760774364521500000000",
        #       "currentPrice": "4083.7744580000000",
        #       "maxPrice": "4218.0241700000000",
        #       "minPrice": "3786.9124050000000",
        #       "startPrice": "3830.5800220000000",
        #       "marketPlatform": 0
        #     },
        #     "BTC_IRT": {
        #       "market": "BTC_IRT",
        #       "marketId": 8,
        #       "marketVolume": "27140908320.17800246693400000000000000",
        #       "currentPrice": "12909088630.0000000000000",
        #       "maxPrice": "13213902170.0000000000000",
        #       "minPrice": "12000000000.0000000000000",
        #       "startPrice": "12752332240.0000000000000",
        #       "marketPlatform": 0
        #     },
        #     ...
        #   }
        # }
        data = self.safe_dict(response, 'data', {})
        marketKeys = list(data.keys())
        result = []
        for i in range(0, len(marketKeys)):
            marketId = marketKeys[i]
            marketData = data[marketId]
            market = self.parse_market(marketData)
            result.append(market)
        return result

    def parse_market(self, market) -> Market:
        #  {
        #    "market": "BTC_IRT",
        #    "marketId": 8,
        #    "marketVolume": "27140908320.17800246693400000000000000",
        #    "currentPrice": "12909088630.0000000000000",
        #    "maxPrice": "13213902170.0000000000000",
        #    "minPrice": "12000000000.0000000000000",
        #    "startPrice": "12752332240.0000000000000",
        #    "marketPlatform": 0
        #  }
        id = self.safe_string(market, 'market')
        parts = id.split('_')
        baseId = self.safe_string(parts, 0)
        quoteId = self.safe_string(parts, 1)
        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': 'spot',
            '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://api5.pingi.co/trading/market/prices/
        :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.publicGetMarketPrices(params)
        # Response structure:
        # {
        #   "statusCode": 200,
        #   "ok": True,
        #   "data": {
        #     "ETH_USDT": {
        #       "market": "ETH_USDT",
        #       "marketId": 6,
        #       "marketVolume": "128889.02937760774364521500000000",
        #       "currentPrice": "4083.7744580000000",
        #       "maxPrice": "4218.0241700000000",
        #       "minPrice": "3786.9124050000000",
        #       "startPrice": "3830.5800220000000",
        #       "marketPlatform": 0
        #     },
        #     ...
        #   }
        # }
        data = self.safe_dict(response, 'data', {})
        marketKeys = list(data.keys())
        result = {}
        for i in range(0, len(marketKeys)):
            marketId = marketKeys[i]
            marketData = data[marketId]
            ticker = self.parse_ticker(marketData)
            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://api5.pingi.co/trading/market/prices/
        :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)
        response = self.publicGetMarketPrices(params)
        # Response structure:
        # {
        #   "statusCode": 200,
        #   "ok": True,
        #   "data": {
        #     "BTC_IRT": {
        #       "market": "BTC_IRT",
        #       "marketId": 8,
        #       "marketVolume": "27140908320.17800246693400000000000000",
        #       "currentPrice": "12909088630.0000000000000",
        #       "maxPrice": "13213902170.0000000000000",
        #       "minPrice": "12000000000.0000000000000",
        #       "startPrice": "12752332240.0000000000000",
        #       "marketPlatform": 0
        #     },
        #     ...
        #   }
        # }
        data = self.safe_dict(response, 'data', {})
        tickerData = self.safe_dict(data, market['id'])
        return self.parse_ticker(tickerData, market)

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #   "market": "BTC_IRT",
        #   "marketId": 8,
        #   "marketVolume": "27140908320.17800246693400000000000000",
        #   "currentPrice": "12909088630.0000000000000",
        #   "maxPrice": "13213902170.0000000000000",
        #   "minPrice": "12000000000.0000000000000",
        #   "startPrice": "12752332240.0000000000000",
        #   "marketPlatform": 0
        # }
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'market')
        symbol = self.safe_symbol(marketId, market, '_', marketType)
        last = self.safe_string(ticker, 'currentPrice')
        high = self.safe_string(ticker, 'maxPrice')
        low = self.safe_string(ticker, 'minPrice')
        open = self.safe_string(ticker, 'startPrice')
        baseVolume = self.safe_string(ticker, 'marketVolume')
        # Calculate change and percentage
        change = None
        percentage = None
        if open is not None and last is not None:
            openNum = self.parse_number(open)
            lastNum = self.parse_number(last)
            if openNum is not None and lastNum is not None and openNum > 0:
                change = self.parse_number(self.number_to_string(lastNum - openNum))
                percentage = self.parse_number(self.number_to_string((lastNum - openNum) / openNum * 100))
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': high,
            'low': low,
            'bid': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': None,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': None,
            'info': ticker,
        }, market)

    def fetch_ohlcv(self, symbol: str, timeframe='1d', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        https://api5.pingi.co/trading/udf/history/
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        endTime = Date.now()
        request = {
            'symbol': market['base'] + '/' + market['quote'],
            'resolution': self.safe_string(self.timeframes, timeframe, timeframe),
            'from': (endTime / 1000) - (30 * 24 * 60 * 60),  # 30 days ago
            'to': endTime / 1000,
        }
        if since is not None:
            request['from'] = since / 1000
        request['from'] = self.safe_integer(request, 'from')
        request['to'] = self.safe_integer(request, 'to')
        response = self.publicGetUdfHistory(request)
        # Response structure:
        # {
        #   "c": [12710726290.0, 12732737270.0, ...],  # close prices
        #   "v": [0.015461630724, 0.024055443184, ...],  # volumes
        #   "l": [12702815580.0, 12689256670.0, ...],  # low prices
        #   "h": [12723701120.0, 12752332240.0, ...],  # high prices
        #   "o": [12752332240.0, 12710726290.0, ...],  # open prices
        #   "t": [1760271600, 1760272500, ...]         # timestamps
        # }
        closeList = self.safe_list(response, 'c', [])
        volumeList = self.safe_list(response, 'v', [])
        lowList = self.safe_list(response, 'l', [])
        highList = self.safe_list(response, 'h', [])
        openList = self.safe_list(response, 'o', [])
        timestampList = self.safe_list(response, 't', [])
        ohlcvs = []
        for i in range(0, len(openList)):
            ohlcvs.append([
                self.safe_timestamp(timestampList, i),
                self.safe_number(openList, i),
                self.safe_number(highList, i),
                self.safe_number(lowList, i),
                self.safe_number(closeList, i),
                self.safe_number(volumeList, i),
            ])
        return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)

    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 path == 'market/prices':
            url = url + '/'
        if path == 'udf/history':
            url = url + '/?' + self.urlencode(query)
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
