# -*- 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


class coingecko (Exchange):

    def describe(self):
        return self.deep_extend(super(coingecko, self).describe(), {
            'id': 'coingecko',
            'name': 'CoinGecko',
            'rateLimit': 67,  # 15 requests per second
            'version': 'v3',
            'countries': ['SG'],
            'has': {
                'CORS': False,
                'publicAPI': True,
                'privateAPI': False,
                'cancelOrder': False,
                'createDepositAddress': False,
                'createOrder': False,
                'deposit': False,
                'fetchBalance': False,
                'fetchClosedOrders': False,
                'fetchCurrencies': True,
                'fetchDepositAddress': False,
                'fetchMarkets': True,
                'fetchMyTrades': False,
                'fetchOHLCV': False,
                'fetchOpenOrders': False,
                'fetchOrder': False,
                'fetchOrderBook': False,
                'fetchL2OrderBook': False,
                'fetchOrders': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchBidsAsks': False,
                'fetchTrades': False,
                'withdraw': False,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/2256515/43684626-2318304a-98d6-11e8-9b80-e46e9d248976.png',
                'api': {
                    'public': 'https://api.coingecko.com/api',
                },
                'www': 'https://coingecko.com',
                'doc': 'https://www.coingecko.com/api/docs/v3',
            },
            'requiredCredentials': {
                'apiKey': False,
                'secret': False,
            },
            'api': {
                'public': {
                    'get': [
                        'ping',
                        'coins',
                        'coins/list',
                        'coins/markets',
                        'coins/{id}',
                        'coins/{id}/history',
                        'coins/{id}/market_chart',
                        'exchange_rates',
                        'global',
                    ],
                },
            },
            'options': {
                # hardcoding is deprecated, we should fetch self list from coingecko itself
                'vsCurrencies': [
                    'AED',
                    'ARS',
                    'AUD',
                    'BRL',
                    'BTC',
                    'CAD',
                    'CHF',
                    'CLP',
                    'CNY',
                    'CZK',
                    'DKK',
                    'ETH',
                    'EUR',
                    'GBP',
                    'HKD',
                    'HUF',
                    'IDR',
                    'ILS',
                    'INR',
                    'JPY',
                    'KRW',
                    'KWD',
                    'LKR',
                    'MXN',
                    'MYR',
                    'NOK',
                    'NZD',
                    'PHP',
                    'PKR',
                    'PLN',
                    'RUB',
                    'SAR',
                    'SEK',
                    'SGD',
                    'THB',
                    'TRY',
                    'TWD',
                    'USD',
                    'XAG',
                    'XAU',
                    'XDR',
                    'ZAR',
                ],
            },
        })

    def fetch_markets(self, params={}):
        coins = self.publicGetCoinsList()
        markets = []
        for i in range(0, len(coins)):
            coin = coins[i]
            vsCurrencies = self.options['vsCurrencies']
            for j in range(0, len(vsCurrencies)):
                markets.append({
                    'id': coin['id'] + '/' + vsCurrencies[j].lower(),
                    'symbol': coin['symbol'].upper() + '/' + vsCurrencies[j],
                    'base': coin['symbol'].upper(),
                    'quote': vsCurrencies[j],
                    'baseId': coin['id'],
                    'quoteId': vsCurrencies[j].lower(),
                    'info': coin,
                })
        return markets

    def fetch_currencies(self):
        coins = self.publicGetCoins()
        currencies = {}
        for i in range(0, len(coins)):
            coin = coins[i]
            symbol = coin['symbol'].upper()
            currencies[symbol] = {
                'id': coin['id'],
                'code': symbol,
                'info': coin,
                'name': coin['name'],
                'active': True,
                'fee': None,
                'precision': 8,
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': None,
                        'max': None,
                    },
                },
            }
        return currencies

    def fetch_tickers(self, currency='USD', params={}):
        markets = self.publicGetCoinsMarkets(self.extend(params, {'vs_currency': currency}))
        tickers = {}
        timestamp = self.milliseconds()
        for i in range(0, len(markets)):
            market = markets[i]
            symbol = market['symbol'].upper() + '/' + currency
            tickers[symbol] = self.parse_ticker(market, symbol, timestamp)
        return tickers

    def fetch_ticker(self, symbol, params={}):
        self.load_markets()
        baseCurrency = self.markets[symbol]['baseId']
        vsCurrency = self.markets[symbol]['quoteId']
        timestamp = self.milliseconds()
        market = self.publicGetCoinsMarkets(self.extend(params, {'ids': baseCurrency, 'vs_currency': vsCurrency}))
        return self.parse_ticker(market[0], symbol, timestamp)

    def parse_ticker(self, market, symbol, timestamp):
        return {
            'symbol': symbol,
            'info': market,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': market['high_24h'],
            'low': market['low_24h'],
            'bid': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': None,
            'last': None,
            'previousClose': None,
            'change': float(market['price_change_24h']),
            'percentage': float(market['price_change_percentage_24h']),
            'average': None,
            'baseVolume': None,
            'quoteVolume': market['total_volume'],
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api'][api] + '/' + self.version + '/' + self.implode_params(path, params)
        query = self.omit(params, self.extract_params(path))
        if query:
            url += '?' + self.urlencode(query)
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
