# -*- 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
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import BadSymbol


class felixo(Exchange):

    def describe(self):
        return self.deep_extend(super(felixo, self).describe(), {
            'id': 'felixo',
            'name': 'Felixo',
            'countries': ['TR'],
            'version': 'v1',
            # 'rateLimit': None,
            'has': {
                'cancelOrder': False,
                'createLimitOrder': False,
                'createMarketOrder': False,
                'createOrder': False,
                'fetchBalance': False,
                # 'fetchClosedOrders': False,
                'fetchMarkets': 'emulated',
                # 'fetchMyTrades': True,
                'fetchOHLCV': False,
                # 'fetchOpenOrders': True,
                # 'fetchOrder': True,
                # 'fetchOrders': True,
                # 'fetchOrderTrades': False,
                'fetchTicker': False,
                'fetchTickers': True,
                'fetchTrades': False,
            },
            'urls': {
                'logo': None,
                'api': {
                    'public': 'https://api.felixo.com',
                    'private': 'https://api.felixo.com',
                },
                'www': 'https://www.felixo.com',
                'doc': 'https://www.felixo.com/static/docs/api/index.html',
                'fees': [
                    'https://www.felixo.com/en/fees-comission-chart',
                    'https://www.felixo.com/en/limits',
                ],
                'referral': None,
            },
            'api': {
                'public': {
                    'get': [
                        'time',
                        'ticker',
                        'orderbook',
                    ],
                },
                'private': {
                    'get': [
                        'account/balances',
                        'openorders',
                    ],
                    'post': [
                        'order',
                    ],
                    'delete': [
                        'order',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': True,
                    'percentage': True,
                    'maker': 0.002,
                    'taker': 0.002,
                },
            },
            'exceptions': {
                'exact': {
                },
                'broad': {
                },
            },
            'options': {
                'symbol': {
                    'quoteIds': ['USDT', 'USDC', 'TRY', 'BTC', 'FLX'],
                    'reversed': False,
                },
            },
            'commonCurrencies': {
            },
        })

    def fetch_markets(self, params={}):
        response = self.publicGetTicker(params)
        #  [
        #      {
        #          "pair": "BTCTRY",
        #          ...
        #      }
        #  ]
        result = []
        for i in range(0, len(response)):
            market = response[i]
            id = self.safe_string(market, 'pair')
            parsed = self.parse_symbol_id_joined(id)
            baseId = parsed['baseId']
            quoteId = parsed['quoteId']
            base = parsed['base']
            quote = parsed['quote']
            symbol = base + '/' + quote
            precision = {
                'amount': None,
                'price': None,
            }
            result.append({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': True,
                'info': market,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                },
            })
        return result

    def fetch_tickers(self, symbols=None, params={}):
        self.load_markets()
        response = self.publicGetTicker(params)
        #  [
        #      {
        #          "pair": "BTCTRY",
        #          ...
        #      }
        #  ]
        return self.parse_tickers(response, symbols)

    def parse_ticker(self, ticker, market=None):
        #  {
        #      "pair": "BTCTRY",
        #      "lastPrice": "43140.00000000",
        #      "openPrice": "43140.00000000",
        #      "highPrice": "43140.00000000",
        #      "lowPrice": "43140.00000000",
        #      "volume": "0.00000000",
        #      "bid": "43140.00000000",
        #      "ask": "43176.00000000",
        #      "timestamp": 1587377957316
        #  }
        timestamp = self.safe_integer(ticker, 'timestamp')
        symbol = None
        marketId = self.safe_string(ticker, 'pair')
        if marketId in self.markets_by_id:
            market = self.markets_by_id[marketId]
        if market is not None:
            symbol = market['symbol']
        last = self.safe_float(ticker, 'lastPrice')
        open = self.safe_float(ticker, 'openPrice')
        change = None
        percentage = None
        average = None
        if last is not None and open is not None:
            change = last - open
            if open > 0:
                percentage = change / open * 100
            average = self.sum(open, last) / 2
        baseVolume = self.safe_float(ticker, 'volume')
        quoteVolume = None
        vwap = None
        if quoteVolume is not None:
            if baseVolume is not None and baseVolume > 0:
                vwap = quoteVolume / baseVolume
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_float(ticker, 'lowPrice'),
            'low': self.safe_float(ticker, 'lowPrice'),
            'bid': self.safe_float(ticker, 'bid'),
            'bidVolume': None,
            'ask': self.safe_float(ticker, 'ask'),
            'askVolume': None,
            'vwap': vwap,
            'open': open,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': percentage,
            'average': average,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }

    def parse_tickers(self, rawTickers, symbols=None):
        tickers = []
        for i in range(0, len(rawTickers)):
            tickers.append(self.parse_ticker(rawTickers[i]))
        return self.filter_by_array(tickers, 'symbol', symbols)

    def fetch_order_book(self, symbol, limit=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit  # Default 100; max 1000. Valid limits: [5, 10, 20, 50, 100, 500, 1000]
        response = self.publicGetOrderbook(self.extend(request, params))
        orderbook = self.parse_order_book(response, self.safe_timestamp(response, 'timestamp'))
        return orderbook

    def parse_symbol_id_joined(self, symbolId):
        # Convert by detecting and converting currencies in symbol
        symbolIdLower = symbolId.lower()
        quoteIds = self.options['symbol']['quoteIds']
        reversed = self.options['symbol']['reversed']
        method = 'startsWith' if reversed else 'endsWith'
        quoteId = None
        baseId = None
        for i in range(0, len(quoteIds)):
            if getattr(self, method)(symbolIdLower, quoteIds[i].lower()):
                quoteId = quoteIds[i]
                break
        if quoteId is None:
            raise BadSymbol(self.id + ' symbolId could not be parsed: ' + symbolId)
        if not reversed:
            baseIdLength = len(symbolId) - len(quoteId)
            baseId = self.slice_string(symbolId, 0, baseIdLength)
            quoteId = self.slice_string(symbolId, baseIdLength)
        else:
            quoteId = self.slice_string(symbolId, 0, len(quoteId))
            baseId = self.slice_string(symbolId, len(quoteId))
        return {
            'baseId': baseId,
            'quoteId': quoteId,
            'base': self.safe_currency_code(baseId),
            'quote': self.safe_currency_code(quoteId),
        }

    def starts_with(self, string, x):
        return self.slice_string(string, 0, len(x)) == x

    def ends_with(self, string, x):
        start = max(0, len(string) - len(x))
        return self.slice_string(string, start) == x

    def slice_string(self, string, start=None, end=None):
        if start is None:
            start = 0
        if end is None:
            end = len(string)
        return string[start:end]

    def nonce(self):
        return self.milliseconds()

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api'][api] + '/' + self.version + '/' + path
        if api == 'public':
            url += '?' + self.urlencode(params)
        else:
            self.check_required_credentials()
            # TODO
            # query['nonce'] = self.nonce()
            # body = self.urlencode(query)
            # headers = {
            #     'Content-Type': 'application/x-www-form-urlencoded',
            #     'Key': self.apiKey,
            #     'Sign': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
            # }
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        # TODO
        if response is None:
            return
        # {"error":"Permission denied."}
        if 'error' in response:
            message = response['error']
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            raise ExchangeError(feedback)  # unknown message
