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


class exnovin(Exchange, ImplicitAPI):

    def describe(self):
        return self.deep_extend(super(exnovin, self).describe(), {
            'id': 'exnovin',
            'name': 'Exnovin',
            'country': ['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': False,
                '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/exnovin/64x64.png',
                'api': {
                    'public': 'https://api.exnovinmarket.com',
                },
                'www': 'https://exnovin.io',
                'doc': [
                    'https://exnovin.io/',
                ],
            },
            'api': {
                'public': {
                    'get': {
                        'v2/pairs': 1,
                        'v1/orderbook': 1,
                    },
                },
            },
            'commonCurrencies': {
                'TMN': 'IRT',
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.001'),
                    'taker': self.parse_number('0.001'),
                },
            },
        })

    def fetch_markets(self, symbols: Strings = None, params={}) -> List[Market]:
        """
        retrieves data on all markets for exnovin
        :see: https://exnovin.io/
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetV2Pairs()
        result = []
        for i in range(0, len(response)):
            market = self.parse_market(response[i])
            result.append(market)
        return result

    def parse_market(self, market) -> Market:
        #         {
        # lastPrice: 214715147,
        # name: "ETH/TMN",
        # tradeAmountDecimals: 6,
        # priceDecimals: 0,
        # maxVariationRatio: "5.00",
        # minCost: "100000",
        # high24: 214755000,
        # low24: 203102000,
        # vol24: 440913246,
        # vol24Base: 2.112867,
        # change24Percentage: 3.4,
        # lastWeekPrices: [
        # 214715000,
        # 206934000,
        # 216552000,
        # 217787000,
        # 216443000,
        # 216832000,
        # 222969000,
        # 225776000
        # ],
        # localeName: "ETH/TMN",
        # zones: [
        # {
        # id: "d4eeb449-7d91-4cae-ad3b-f8b1ef376d1d",
        # label: "Toman",
        # name: "TMN"
        # }
        # ],
        # imageUrl: "https://api.exnovinmarket.com/static-contents/images/icons/d22722b936d9409f9f9b15c7a5a07046.svg",
        # active: True
        # },
        id = self.safe_string(market, 'name')
        baseId, quoteId = id.split('/')
        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
        :see: https://exnovin.io/
        :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.publicGetV2Pairs(params)
        result = {}
        for i in range(0, len(response)):
            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
        :see: https://exnovin.io/
        :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:
        #         {
        # lastPrice: 214715147,
        # name: "ETH/TMN",
        # tradeAmountDecimals: 6,
        # priceDecimals: 0,
        # maxVariationRatio: "5.00",
        # minCost: "100000",
        # high24: 214755000,
        # low24: 203102000,
        # vol24: 440913246,
        # vol24Base: 2.112867,
        # change24Percentage: 3.4,
        # lastWeekPrices: [
        # 214715000,
        # 206934000,
        # 216552000,
        # 217787000,
        # 216443000,
        # 216832000,
        # 222969000,
        # 225776000
        # ],
        # localeName: "ETH/TMN",
        # zones: [
        # {
        # id: "d4eeb449-7d91-4cae-ad3b-f8b1ef376d1d",
        # label: "Toman",
        # name: "TMN"
        # }
        # ],
        # imageUrl: "https://api.exnovinmarket.com/static-contents/images/icons/d22722b936d9409f9f9b15c7a5a07046.svg",
        # active: True
        # },
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'name')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        high = self.safe_float(ticker, 'high24', 0)
        low = self.safe_float(ticker, 'low24', 0)
        last = self.safe_float(ticker, 'lastPrice', 0)
        change = self.safe_float(ticker, 'change24Percentage', 0)
        baseVolume = self.safe_float(ticker, 'vol24Base', 0)
        quoteVolume = self.safe_float(ticker, 'vol24', 0)
        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': last,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    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
        :see: https://exnovin.io/
        :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
        """
        #         {
        # price: "59034.0000000000",
        # amount: "128.0200000000",
        # pair: "USDT/TMN",
        # side: "BUY"
        # },
        # {
        # price: "59032.0000000000",
        # amount: "461.1300000000",
        # pair: "USDT/TMN",
        # side: "BUY"
        # },
        self.load_markets()
        market = self.market(symbol)
        request = {
            'pair': market['id'],
            'limit': 30,
        }
        orderBook = self.publicGetV1Orderbook(request)
        bids = []
        asks = []
        for index in range(0, len(orderBook)):
            if orderBook[index]['side'] == 'BUY':
                bids.append(orderBook[index])
            else:
                asks.append(orderBook[index])
        orderBook = {'bids': bids, 'asks': asks}
        timestamp = Date.now()
        return self.parse_order_book(orderBook, symbol, timestamp, 'bids', 'asks', 'price', 'amount')

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