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


class ramzinex(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(ramzinex, self).describe(), {
            'id': 'ramzinex',
            'name': 'Ramzinex',
            '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,
                'fetchLedger': False,
                'fetchLedgerEntry': False,
                'fetchLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': False,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': False,
                'fetchOrder': False,
                'fetchOrderBook': True,
                '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/ramzinex/64x64.png',
                'api': {
                    'public': 'https://publicapi.ramzinex.com',
                },
                'www': 'https://ramzinex.com/',
                'doc': [
                    'https://api-doc.ramzinex.com/',
                ],
            },
            'timeframes': {
                '1m': '1',
                '5m': '5',
                '15m': '15',
                '30m': '30',
                '1h': '60',
                '3h': '180',
                '4h': '240',
                '6h': '360',
                '12h': '720',
                '1d': 'D',
                '2d': '2D',
                '3d': '3D',
            },
            'api': {
                'public': {
                    'get': {
                        'exchange/api/v1.0/exchange/pairs': 1,
                        'exchange/api/v1.0/exchange/chart/tv/history': 1,
                        'exchange/api/v1.0/exchange/orderbooks': 1,
                    },
                },
            },
            'commonCurrencies': {
                'IRR': 'IRT',
            },
            '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 ramzinex
        https://apidocs.ramzinex.ir/#6ae2dae4a2
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetExchangeApiV10ExchangePairs()
        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:
        # {
        #     'amount_step': 0.00002,
        #     'base_currency_id': 1,
        #     'base_currency_symbol': {
        #         'en': 'btc',
        #         'fa': 'بیت کوین',
        #     },
        #     'base_precision': 5,
        #     'buy': 39909989891,
        #     'crypto_box': 0,
        #     'financial': {
        #         'last24h': {
        #             'base_volume': 0.5642693,
        #             'change_percent': -2.12,
        #             'close': 39836757000,
        #             'highest': 40698025995,
        #             'lowest': 39336170240,
        #             'open': 40698025900,
        #             'quote_volume': 22460381464,
        #         },
        #     },
        #     'icon': 'exchange/img/coins/btc.png',
        #     'logo': 'https://public-assets.ramzinex.com/public/currencies/logo/btc.png',
        #     'name': {
        #         'en': 'bitcoin/rial',
        #         'fa': 'بیت کوین',
        #     },
        #     'pair_id': 2,
        #     'price_precision': 0,
        #     'price_step': 39999989,
        #     'quote_currency_id': 2,
        #     'quote_currency_symbol': {
        #         'en': 'irr',
        #         'fa': 'ریال',
        #     },
        #     'quote_precision': 0,
        #     'sell': 39999989872,
        #     'show_order': 50,
        #     'tv_symbol': {
        #         'international': 'BINANCE:BTCUSDT',
        #         'ramzinex': 'btcirr',
        #     },
        #     'url_name': 'bitcoin-btc',
        #     'web_link': 'https://ramzinex.com/exchange/orderbook/2',
        # }
        baseAsset = self.safe_dict(market, 'base_currency_symbol')
        quoteAsset = self.safe_dict(market, 'quote_currency_symbol')
        baseId = self.safe_string_upper(baseAsset, 'en')
        quoteId = self.safe_string_upper(quoteAsset, 'en')
        id = self.safe_value(market, 'pair_id')
        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': 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://api-doc.ramzinex.com/#get-5
        :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.publicGetExchangeApiV10ExchangePairs()
        markets = self.safe_list(response, 'data')
        result = {}
        for i in range(0, len(markets)):
            market = markets[i]
            if not market or not market['financial'] or market['financial'] == 0:
                continue
            ticker = self.parse_ticker(market)
            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://api-doc.ramzinex.com/#get-5
        :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 = {
            'pair_id': market['id'],
        }
        response = self.publicGetExchangeApiV10ExchangePairs(request)
        markets = self.safe_dict(response, 'data')
        ticker = self.parse_ticker(markets)
        return ticker

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #     'amount_step': 0.00002,
        #     'base_currency_id': 1,
        #     'base_currency_symbol': {
        #         'en': 'btc',
        #         'fa': 'بیت کوین',
        #     },
        #     'base_precision': 5,
        #     'buy': 39909989891,
        #     'crypto_box': 0,
        #     'financial': {
        #         'last24h': {
        #             'base_volume': 0.5642693,
        #             'change_percent': -2.12,
        #             'close': 39836757000,
        #             'highest': 40698025995,
        #             'lowest': 39336170240,
        #             'open': 40698025900,
        #             'quote_volume': 22460381464,
        #         },
        #     },
        #     'icon': 'exchange/img/coins/btc.png',
        #     'logo': 'https://public-assets.ramzinex.com/public/currencies/logo/btc.png',
        #     'name': {
        #         'en': 'bitcoin/rial',
        #         'fa': 'بیت کوین',
        #     },
        #     'pair_id': 2,
        #     'price_precision': 0,
        #     'price_step': 39999989,
        #     'quote_currency_id': 2,
        #     'quote_currency_symbol': {
        #         'en': 'irr',
        #         'fa': 'ریال',
        #     },
        #     'quote_precision': 0,
        #     'sell': 39999989872,
        #     'show_order': 50,
        #     'tv_symbol': {
        #         'international': 'BINANCE:BTCUSDT',
        #         'ramzinex': 'btcirr',
        #     },
        #     'url_name': 'bitcoin-btc',
        #     'web_link': 'https://ramzinex.com/exchange/orderbook/2',
        # }
        tickerinfo = self.safe_dict(ticker, 'financial')
        tickerinfo = self.safe_dict(tickerinfo, 'last24h')
        marketType = 'spot'
        marketId = self.safe_value(ticker, 'pair_id')
        marketinfo = self.market(marketId)
        symbol = self.safe_symbol(marketId, market, None, marketType)
        high = self.safe_float(tickerinfo, 'highest')
        low = self.safe_float(tickerinfo, 'lowest')
        bid = self.safe_float(ticker, 'sell')
        ask = self.safe_float(ticker, 'buy')
        open = self.safe_float(tickerinfo, 'open')
        close = self.safe_float(tickerinfo, 'close')
        change = self.safe_float(tickerinfo, 'change_percent')
        last = self.safe_float(ticker, 'buy')
        quoteVolume = self.safe_float(tickerinfo, 'quote_volume')
        baseVolume = self.safe_float(tickerinfo, 'base_volume')
        if marketinfo['quote'] == 'IRT':
            high = high * 10 if high else 0
            low = low / 10 if low else 0
            bid = bid / 10 if bid else 0
            ask = ask / 10 if ask else 0
            open = open / 10 if open else 0
            close = close / 10 if close else 0
            last = last / 10 if last else 0
            quoteVolume = quoteVolume / 10 if quoteVolume else 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': open,
            'close': close,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    def fetch_ohlcv(self, symbol: str, timeframe='1m', 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://api-doc.ramzinex.com/
        :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)
        if market['quote'] == 'IRT':
            symbol = market['base'] + 'IRR'
        endTime = Date.now()
        request = {
            'symbol': symbol.replace('/', ''),
            'from': (endTime / 1000) - (24 * 60 * 60),
            'to': endTime / 1000,
            'resolution': self.safe_string(self.timeframes, timeframe, timeframe),
            # 'limit': 500,
        }
        if since is not None:
            request['from'] = since / 1000
        request['from'] = self.safe_integer(request, 'from')
        request['to'] = self.safe_integer(request, 'to')
        if timeframe is not None:
            request['resolution'] = self.safe_string(self.timeframes, timeframe, timeframe)
        response = self.publicGetExchangeApiV10ExchangeChartTvHistory(request)
        openList = self.safe_value(response, 'o', [])
        highList = self.safe_list(response, 'h', [])
        lastList = self.safe_list(response, 'l', [])
        closeList = self.safe_list(response, 'c', [])
        volumeList = self.safe_list(response, 'v', [])
        timestampList = self.safe_list(response, 't', [])
        ohlcvs = []
        for i in range(0, len(openList)):
            if market['quote'] == 'IRT':
                openList[i] = openList[i] / 10 if openList[i] else 0
                highList[i] = highList[i] / 10 if highList[i] else 0
                lastList[i] = lastList[i] / 10 if lastList[i] else 0
                closeList[i] = closeList[i] / 10 if closeList[i] else 0
                volumeList[i] = volumeList[i] / 10 if volumeList[i] else 0
            ohlcvs.append([
                timestampList[i],
                openList[i],
                highList[i],
                lastList[i],
                closeList[i],
                volumeList[i],
            ])
        return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)

    def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data for multiple markets
        https://api-doc.ramzinex.com/#get
        :param str[]|None symbols: list of unified market symbols, all symbols fetched if None, default is None
        :param int [limit]: max number of entries per orderbook to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbol
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'pair_id': market['id'],
        }
        response = self.publicGetExchangeApiV10ExchangeOrderbooks(request)
        orderbook = self.safe_dict(response, 'data')
        if market['quote'] == 'IRT':
            bids = self.safe_list(orderbook, 'sells')
            asks = self.safe_list(orderbook, 'buys')
            for i in range(0, len(bids)):
                bids[i][0] = bids[i][0] / 10 if bids[i][0] else 0
            for i in range(0, len(asks)):
                asks[i][0] = asks[i][0] / 10 if asks[i][0] else 0
            orderbook['buys'] = asks
            orderbook['sells'] = bids
        timestamp = Date.now()
        return self.parse_order_book(orderbook, symbol, timestamp, 'sells', 'buys')

    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
        pair_id = self.safe_string(params, 'pair_id')
        if pair_id is not None:
            url = url + '/' + pair_id
        if path == 'exchange/api/v1.0/exchange/chart/tv/history':
            url = self.urls['api']['public'] + '/' + path + '?' + self.urlencode(query)
        if path == 'exchange/api/v1.0/exchange/orderbooks':
            url = url + '/buys_sells'
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
