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


class arzplus(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(arzplus, self).describe(), {
            'id': 'arzplus',
            'name': 'Arzplus',
            '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/arzplus/64x64.png',
                'api': {
                    'public': 'https://api.arzplus.net',
                },
                'www': 'https://arzplus.net',
                'doc': [
                    'https://arzplus.net',
                ],
            },
            'timeframes': {
                '1h': '60',
                '1d': '1D',
            },
            'api': {
                'public': {
                    'get': {
                        'api/v1/market/symbols': 1,
                        'api/v1/market/tradingview/ohlcv': 1,
                        'api/v1/market/depth': 1,
                        'api/v1/market/irt/info': 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 arzplus
        https://api.arzplus.net/
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        request = {
            'stats': '1',
            'enable': 'true',
        }
        typedRequest = self.safe_string(params, 'type', 'spot')
        response = []
        otcMarkets = []
        if typedRequest == 'otc':
            otcMarkets = self.publicGetApiV1MarketIrtInfo(request)
        else:
            response = self.publicGetApiV1MarketSymbols(request)
        result = []
        for i in range(0, len(response)):
            market = self.parse_market(response[i])
            result.append(market)
        for i in range(0, len(otcMarkets)):
            marketdata = otcMarkets[i]
            marketdata['quote'] = 'IRT'
            marketdata['id'] = 'OTC_' + marketdata['symbol'] + marketdata['quote']
            parsedMarket = self.parse_otc_markets(marketdata)
            result.append(parsedMarket)
        return result

    def parse_market(self, market, type: MarketType = 'spot') -> Market:
        if type == 'otc':
            return self.parse_otc_markets(market)
        return self.parse_spot_market(market)

    def parse_spot_market(self, market) -> Market:
        # {
        #     'name': 'USDTIRT',
        #     'asset': {
        #         'id': 2,
        #         'symbol': 'USDT',
        #         'precision': 8,
        #         'step_size': 8,
        #         'name': 'tether',
        #         'name_fa': 'تتر',
        #         'logo': 'https://cdn.arzplus.net/core-static/coins/USDT.png',
        #         'original_symbol': 'USDT',
        #         'original_name_fa': 'تتر',
        #         'trading_view_symbol': '',
        #     },
        #     'base_asset': {
        #         'id': 1,
        #         'symbol': 'IRT',
        #         'precision': 0,
        #         'step_size': 8,
        #         'name': 'toman',
        #         'name_fa': 'تومان',
        #         'logo': 'https://cdn.arzplus.net/core-static/coins/IRT.png',
        #         'original_symbol': 'IRT',
        #         'original_name_fa': 'تومان',
        #         'trading_view_symbol': '',
        #     },
        #     'enable': True,
        #     'price': '59165',
        #     'change': '-246',
        #     'change_percent': '-0.41',
        #     'high': '59619',
        #     'low': '58750',
        #     'volume': '215768.82',
        #     'base_volume': '12757163742',
        #     'bookmark': True,
        # }
        id = self.safe_string(market, 'name')
        baseAsset = self.safe_dict(market, 'asset')
        quoteAsset = self.safe_dict(market, 'base_asset')
        baseId = self.safe_string(baseAsset, 'symbol')
        quoteId = self.safe_string(quoteAsset, 'symbol')
        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 parse_otc_markets(self, market) -> Market:
        #  {
        #    symbol: "BTC",
        #    ask: "13877900000",
        #    bid: "13860999995",
        #    name: "bitcoin"
        #    qoute: "IRT",
        #    id: "OTC_BTCIRT"
        # },
        baseAsset = self.safe_string(market, 'symbol')
        quoteAsset = self.safe_string(market, 'quote')
        baseId = baseAsset
        quoteId = quoteAsset
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        id = self.safe_string(market, 'id')
        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,
        }

    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.arzplus.net/
        :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>`
        """
        marketType = self.safe_string(params, 'type', 'spot')
        self.load_markets(False, {'type': marketType})
        if symbols is not None:
            symbols = self.market_symbols(symbols)
        result = {}
        if marketType == 'otc':
            otcMarkets = self.publicGetApiV1MarketIrtInfo(params)
            for i in range(0, len(otcMarkets)):
                marketdata = otcMarkets[i]
                marketdata['quote'] = 'IRT'
                marketdata['id'] = 'OTC_' + marketdata['symbol'] + marketdata['quote']
                parsedMarket = self.parse_otc_ticker(marketdata)
                symbol = parsedMarket['symbol']
                result[symbol] = parsedMarket
            return self.filter_by_array_tickers(result, 'symbol', symbols)
        response = self.publicGetApiV1MarketSymbols(params)
        for i in range(0, len(response)):
            request = {
                'symbol': response[i]['name'],
            }
            assetDetails = self.publicGetApiV1MarketSymbols(request)
            ticker = self.parse_ticker(assetDetails)
            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.arzplus.net/
        :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>`
        """
        marketType = self.safe_string(params, 'type', 'spot')
        if marketType == 'otc':
            raise Error('OTC markets are not supported')
        self.load_markets(False, {'type': marketType})
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = self.publicGetApiV1MarketSymbols(request)
        ticker = self.parse_ticker(response)
        return ticker

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #     'name': 'USDTIRT',
        #     'asset': {
        #         'id': 2,
        #         'symbol': 'USDT',
        #         'precision': 8,
        #         'step_size': 8,
        #         'name': 'tether',
        #         'name_fa': 'تتر',
        #         'logo': 'https://cdn.arzplus.net/core-static/coins/USDT.png',
        #         'original_symbol': 'USDT',
        #         'original_name_fa': 'تتر',
        #         'trading_view_symbol': '',
        #     },
        #     'base_asset': {
        #         'id': 1,
        #         'symbol': 'IRT',
        #         'precision': 0,
        #         'step_size': 8,
        #         'name': 'toman',
        #         'name_fa': 'تومان',
        #         'logo': 'https://cdn.arzplus.net/core-static/coins/IRT.png',
        #         'original_symbol': 'IRT',
        #         'original_name_fa': 'تومان',
        #         'trading_view_symbol': '',
        #     },
        #     'enable': True,
        #     'price': '59165',
        #     'change': '-246',
        #     'change_percent': '-0.41',
        #     'high': '59619',
        #     'low': '58750',
        #     'volume': '215768.82',
        #     'base_volume': '12757163742',
        #     'bookmark': True,
        # }
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'name')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        high = self.safe_float(ticker, 'high', 0)
        low = self.safe_float(ticker, 'low', 0)
        last = self.safe_float(ticker, 'price', 0)
        change = self.safe_float(ticker, 'change_percent', 0)
        baseVolume = self.safe_float(ticker, 'volume', 0)
        quoteVolume = self.safe_float(ticker, 'base_volume', 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 parse_otc_ticker(self, ticker, market: Market = None) -> Ticker:
        #        {
        # id: "BTCUSDT",
        # symbol: "BTC",
        # ask: "13877900000",
        # bid: "13860999995",
        # name: "bitcoin"
        # quote: "IRT"
        # }
        marketType = 'otc'
        marketId = self.safe_string(ticker, 'id')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        bid = self.safe_float(ticker, 'bid', 0)
        ask = self.safe_float(ticker, 'ask', 0)
        last = self.safe_float(ticker, 'ask', 0)
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': None,
            'low': None,
            'bid': bid,
            'bidVolume': None,
            'ask': ask,
            'askVolume': None,
            'vwap': None,
            'open': last,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': None,
            'quoteVolume': None,
            'info': ticker,
        }, market)

    def fetch_ohlcv(self, symbol: str, timeframe='1h', 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.arzplus.net/
        :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(False, {'type': 'otc'})
        market = self.market(symbol)
        endTime = Date.now()
        request = {
            'symbol': market['id'],
            'from': (endTime / 1000) - (24 * 60 * 60),
            'to': endTime / 1000,
            'resolution': self.safe_string(self.timeframes, timeframe, timeframe),
            'countBack': 300,
        }
        if since is not None:
            request['from'] = since / 1000
        if limit is not None:
            request['countBack'] = limit
        if timeframe is not None:
            request['resolution'] = self.safe_string(self.timeframes, timeframe, timeframe)
        request['from'] = self.safe_integer(request, 'from')
        request['to'] = self.safe_integer(request, 'to')
        response = self.publicGetApiV1MarketTradingviewOhlcv(request)
        ohlcvs = []
        for i in range(0, len(response)):
            ohlcvs.append([
                self.safe_value(response[i], 'time'),
                self.safe_value(response[i], 'open'),
                self.safe_value(response[i], 'high'),
                self.safe_value(response[i], 'low'),
                self.safe_value(response[i], 'close'),
                self.safe_value(response[i], 'volume'),
            ])
        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.arzplus.net/
        :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(False, {'type': 'otc'})
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        orderBook = self.publicGetApiV1MarketDepth(request)
        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
        symbol = self.safe_string(params, 'symbol')
        stats = self.safe_value(params, 'stats')
        if stats is not None:
            url = url + '?' + self.urlencode(query)
        if path == 'api/v1/market/tradingview/ohlcv':
            url = url + '?' + self.urlencode(query)
        elif symbol is not None:
            url = url + '/' + symbol
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
