# -*- 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 base64
import hashlib


class bitbns(Exchange):

    def describe(self):
        return self.deep_extend(super(bitbns, self).describe(), {
            'id': 'bitbns',
            'name': 'BitBns Exchange',
            'countries': ['IN'],
            'version': '1.0',
            'has': {
                # 'CORS': False,
                'fetchCurrencies': False,
                'fetchTicker': True,  # Can be emulated on fetchTickers if necessary
                'fetchTickers': True,
                'fetchTrades': True,
                'fetchTradingFees': False,
                'fetchBalance': True,
                'createOrder': True,
                'cancelOrder': True,
                'fetchOpenOrders': True,
                'fetchMyTrades': True,
                'fetchDepositAddress': False,
                'fetchWithdrawals': False,
                'fetchDeposits': False,
                'fetchClosedOrders': False,
                'fetchL2OrderBook': False,
                'fetchOHLCV': 'emulated',
                'fetchOrder': True,
                'editOrder': False,
                'fetchTransactions': False,
                'fetchLedger': False,
                'withdraw': False,
                'fetchMarkets': True,
                'fetchOrderBook': True,
            },
            'urls': {
                'logo': 'https://bitbns.com/assets/img/logos/bitbns.svg',
                'api': {
                    'public': 'https://bitbns.com/order/',
                    'private': 'https://api.bitbns.com/api/trade/v2',
                    'private1': 'https://api.bitbns.com/api/trade/v1',
                },
                'www': 'https://bitbns.com/',
                'doc': 'https://github.com/bitbns-official/node-bitbns-api',
                'fees': 'https://bitbns.com/fees/',
            },
            'api': {
                'public': {'get': [
                    'fetchOrderBook',
                    'fetchMarkets',
                    'fetchTickers',
                    'fetchTrades',
                ]},
                'private': {'post': [
                    'orders',
                    'cancel',
                    'getordersnew',
                ]},
                'private1': {'post': [
                    'orderStatus',
                    'listOpenOrders',
                    'currentCoinBalance',
                    'listExecutedOrders',
                ]},
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': 0.0025,
                    'taker': 0.0025,
                },
            },
            # 'verbose': True,
            # 'proxy': '',
            'apiKey': '',
            'secret': '',
        })

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = ''
        if api == 'private1' or api == 'private':
            if api == 'private1':
                # Generate complete url
                url = self.urls['api'][api] + '/' + path + '/' + self.safe_string(params, 'symbol')
            if api == 'private':
                url = self.urls['api'][api] + '/' + self.implode_params(path, params)
            if method == 'POST':
                body = self.json(params)
            # Generate payload
            timeStamp_nonce = self.milliseconds()
            data = {
                'symbol': '/' + path + '/' + self.safe_string(params, 'symbol'),
                'timeStamp_nonce': timeStamp_nonce,
                'body': body,
            }
            payload = base64.b64encode(self.encode(self.json(data)))
            # Generate signature from payload
            signature = self.hmac(payload, self.encode(self.secret), hashlib.sha512, 'hex')
            # Init headers
            headers = {}
            # Attach headers
            headers['X-BITBNS-APIKEY'] = self.apiKey
            headers['X-BITBNS-PAYLOAD'] = self.decode(payload)
            headers['X-BITBNS-SIGNATURE'] = signature
            headers['Accept'] = 'application/json'
            headers['Accept-Charset'] = 'utf-8'
            headers['content-type'] = 'application/x-www-form-urlencoded'
        else:
            url = self.urls['api'][api] + path
            if params:
                url += '?' + self.urlencode(params)
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def fetch_markets(self, params={}):
        data = self.publicGetFetchMarkets(params)
        for i in range(0, len(data)):
            if data[i]['quote'] == 'USDT':
                data[i]['us_symbol'] = data[i]['base'] + '_' + data[i]['quote']
        return data

    def fetch_tickers(self, symbols=None, params={}):
        data = self.publicGetFetchTickers(params)
        fetchedSymbols = list(data.keys())
        result = {}
        for i in range(0, len(fetchedSymbols)):
            ticker = data[fetchedSymbols[i]]
            if symbols is None or self.in_array(fetchedSymbols[i], symbols):
                keys = list(ticker.keys())
                for j in range(0, len(keys)):
                    if not ticker[keys[j]]:
                        ticker[keys[j]] = None
                result[fetchedSymbols[i]] = ticker
        return result

    def fetch_ticker(self, symbol=None, params={}):
        tickers = self.fetch_tickers(None, params)
        return self.safe_value(tickers, symbol)

    def fetch_trades(self, symbol, since=None, limit=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        excgSymbol = market['id']
        request = {
            'symbol': excgSymbol,
            'since': since,
            'limit': limit,
        }
        trades = self.publicGetFetchTrades(self.extend(request, params))
        for i in range(0, len(trades)):
            trades[i]['symbol'] = symbol
            trades[i]['id'] = self.safe_string(trades[i], 'id')
            keys = list(trades[i].keys())
            for k in range(0, len(keys)):
                if not self.safe_string(trades[i], keys[k]):
                    trades[i][keys[k]] = None
        return trades

    def fetch_order_book(self, symbol=None, limit=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        excgSymbol = market['id']
        request = {
            'symbol': excgSymbol,
            'limit': limit,
        }
        return self.publicGetFetchOrderBook(self.extend(request, params))

    def create_order(self, symbol, type, side, amount, price=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['id']
        request = {
            'symbol': tradingSymbol,
            'side': side.upper(),
            'quantity': amount,
            'rate': price,
        }
        if market['quote'] == 'USDT':
            request['symbol'] = market['us_symbol']
        resp = self.privatePostOrders(self.extend(request, params))
        return {
            'info': resp,
            'id': self.safe_string(resp, 'id'),
        }

    def cancel_order(self, id, symbol=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['id']
        request = {
            'symbol': tradingSymbol,
            'entry_id': id,
        }
        if market['quote'] == 'USDT':
            request['symbol'] = market['us_symbol']
        if market['quote'] == 'USDT':
            request['side'] = 'usdtcancelOrder'
        else:
            request['side'] = 'cancelOrder'
        return self.privatePostCancel(self.extend(request, params))

    def parse_order(self, order, market=None):
        orderData = self.safe_value(order, 'data')[0]
        orderObj = {
            'id': self.safe_string(orderData, 'entry_id'),  # string
            'datetime': self.safe_string(orderData, 'time'),  # ISO8601 datetime of 'timestamp' with milliseconds
            'timestamp': self.parse8601(self.safe_string(orderData, 'time')),
            'lastTradeTimestamp': None,  # Unix timestamp of the most recent trade on self order
            'symbol': self.safe_string(market, 'symbol'),      # symbol
            'type': 'limit',        # 'market', 'limit'
            'side': self.safe_string(orderData, 'side'),          # 'buy', 'sell'
            'price': self.safe_float(orderData, 'rate'),    # float price in quote currency
            'amount': self.safe_float(orderData, 'amount'),           # ordered amount of base currency
            'filled': self.safe_float(orderData, 'filled'),           # filled amount of base currency
            'remaining': self.safe_float(orderData, 'remaining'),  # remaining amount to fill
            'cost': self.safe_float(orderData, 'filled') * self.safe_float(orderData, 'avg_cost'),   # 'filled' * 'price'(filling price used where available)
            'trades': None,         # a list of order trades/executions
            'fee': self.safe_float(orderData, 'fee'),
            'info': order,              # the original unparsed order structure as is
        }
        status = self.safe_integer(orderData, 'status')
        if status == 0:
            orderObj['status'] = 'open'
        elif status == -1:
            orderObj['status'] = 'canceled'
        elif status == 2:
            orderObj['status'] = 'closed'
        return orderObj

    def fetch_order(self, id, symbol=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['id']
        request = {
            'symbol': tradingSymbol,
            'entry_id': id,
        }
        resp = self.private1PostOrderStatus(self.extend(request, params))
        return self.parse_order(resp, market)

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['id']
        request = {
            'symbol': tradingSymbol,
            'page': 0,
        }
        if market['quote'] == 'USDT':
            request['symbol'] = market['us_symbol']
        if market['quote'] == 'USDT':
            request['side'] = 'usdtListOpenOrders'
        else:
            request['side'] = 'listOpenOrders'
        resp = self.privatePostGetordersnew(self.extend(request, params))
        orders = self.safe_value(resp, 'data')
        openOrders = []
        for i in range(0, len(orders)):
            orderObj = {
                'id': self.safe_string(orders[i], 'entry_id'),  # string
                'datetime': self.safe_string(orders[i], 'time'),  # ISO8601 datetime of 'timestamp' with milliseconds
                'timestamp': self.parse8601(self.safe_string(orders[i], 'time')),
                'lastTradeTimestamp': None,  # Unix timestamp of the most recent trade on self order
                'symbol': symbol,      # symbol
                'type': 'limit',        # 'market', 'limit'
                'side': None,          # 'buy', 'sell'
                'price': self.safe_value(orders[i], 'rate'),    # float price in quote currency
                'amount': None,           # ordered amount of base currency
                'filled': None,           # filled amount of base currency
                'remaining': self.safe_value(orders[i], 'btc'),  # remaining amount to fill
                'cost': None,   # 'filled' * 'price'(filling price used where available)
                'trades': None,         # a list of order trades/executions
                'fee': None,
                'info': resp,              # the original unparsed order structure as is
            }
            status = self.safe_integer(orders[i], 'status')
            if status == 0:
                orderObj['status'] = 'open'
            elif status == -1:
                orderObj['status'] = 'canceled'
            elif status == 2:
                orderObj['status'] = 'closed'
            orderObj['side'] = orders[i].type == 'sell' if 1 else 'buy'
            orderObj['amount'] = orderObj['price'] * orderObj['remaining']
            openOrders.append(orderObj)
        return openOrders

    def fetch_balance(self, params={}):
        self.load_markets()
        codes = list(self.omit(self.currencies, ['INR']).keys())
        # Body for the balance API request
        request = {
            'symbol': 'EVERYTHING',
        }
        # Make the API call for balance
        data = self.private1PostCurrentCoinBalance(self.extend(request, params))
        balances = {}
        balances['info'] = data
        currencybalances = self.safe_value(data, 'data')
        freefiat = self.safe_float(currencybalances, 'availableorderMoney')
        usedfiat = self.safe_float(currencybalances, 'inorderMoney')
        if (freefiat is not None) or (usedfiat is not None):
            balances['INR'] = {
                'free': freefiat,
                'used': usedfiat,
            }
        for i in range(0, len(codes)):
            code = codes[i]
            currency = self.currency(code)
            currencyId = currency['id']
            availableOrderString = 'availableorder' + currencyId
            free = self.safe_float(currencybalances, availableOrderString)
            inorderString = 'inorder' + currencyId
            used = self.safe_float(currencybalances, inorderString)
            if (free is not None) or (used is not None):
                balances[code] = {
                    'free': free,
                    'used': used,
                }
        return self.parse_balance(balances)

    def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        self.load_markets()
        market = self.market(symbol)
        tradingSymbol = market['id']
        if limit is None:
            limit = 0
        if since is not None:
            since = self.iso8601(since)
        request = {
            'symbol': tradingSymbol,
            'page': 0,
        }
        if since is not None:
            request['since'] = since
        resp = self.private1PostListExecutedOrders(self.extend(request, params))
        trades = self.safe_value(resp, 'data')
        result = []
        numOfTrades = len(trades)
        if limit and len(trades) > limit:
            numOfTrades = limit
        for i in range(0, numOfTrades):
            tradeObj = {
                'info': trades[i],
                'id': trades[i]['id'],
                'timestamp': trades[i]['date'],
                'datetime': self.parse8601(trades[i]['date']),
                'symbol': symbol,
                'order': None,
                'type': 'limit',
                'side': None,
                'takerOrMaker': None,
                'price': trades[i]['rate'],
                'amount': trades[i]['amount'],
                'fee': trades[i]['fee'],
            }
            result.append(tradeObj)
        return result
