'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require('./base/Exchange');

//  ---------------------------------------------------------------------------

module.exports = class nokuexchange extends Exchange {

    describe () {
        return this.deepExtend(super.describe(), {
            'id': 'nokuexchange',
            'name': 'NokuExchange',
            'countries': 'CH',
            'enableRateLimit': true,
            'rateLimit': 2000, // milliseconds = seconds * 1000
            'certified': false,
            'has': {
                'cancelAllOrders': false,
                'cancelOrder': true,
                'cancelOrders': false,
                'CORS': false,
                'createDepositAddress': false,
                'createLimitOrder': false,
                'createMarketOrder': false,
                'createOrder': true,
                'deposit': false,
                'editOrder': false,
                'fetchBalance': false,
                'fetchBidsAsks': false,
                'fetchClosedOrders': false,
                'fetchCurrencies': false,
                'fetchDepositAddress': false,
                'fetchDeposits': false,
                'fetchFundingFees': false,
                'fetchL2OrderBook': false,
                'fetchLedger': false,
                'fetchMarkets': false,
                'fetchMyTrades': false,
                'fetchOHLCV': false,
                'fetchOpenOrders': false,
                'fetchOrder': false,
                'fetchOrderBook': false,
                'fetchOrderBooks': false,
                'fetchOrders': true,
                'fetchTicker': false,
                'fetchTickers': false,
                'fetchTrades': false,
                'fetchTradingFee': false,
                'fetchTradingFees': false,
                'fetchTradingLimits': false,
                'fetchTransactions': false,
                'fetchWithdrawals': false,
                'privateAPI': true,
                'publicAPI': true,
                'withdraw': false,
            },
            'urls': {
                'api': 'https://api.noku.exchange',
                'www': 'https://noku.exchange',
                'doc': 'https://docapi.noku.exchange',
            },
            'api': {
                'public': {
                    'get': [
                        'data/instruments',
                        'data/assets',
                        'data/rates',
                        'data/candles/history?symbol={ticker}&resolution={resolution}&from={from}&to={to}',
                    ],
                    'post': [
                        'data/depth',
                        'data/history',
                    ]
                },
                'private': {
                    'get': [
                        'user/limits',
                        'user/type',
                        'user/balance',
                    ],
                    'post': [
                        'exchange/order',
                        'exchange/transactions',
                        'wallet/depositAddress',
                        'wallet/data',
                    ],
                    'put': [
                        'exchange/order',
                        'wallet/withdrawal',
                    ],
                    'delete': [
                        'exchange/order/{market}/{id}',
                    ]
                }
            },
            'version': 'v1',
            'requiredCredentials': {
                'apiKey':     false,
                'secret':     false,
                'uid':        false,
                'login':      false,
                'password':   false,
                'twofa':      false, // 2-factor authentication (one-time password key)
                'privateKey': false, // a "0x"-prefixed hexstring private key for a wallet
                'walletAddress': false, // the wallet address "0x"-prefixed hexstring
                'token':      true, // reserved for HTTP auth in some cases
            },
        }) // return
    } // describe ()

    async fetchDataInstruments () {
        const response = await this.publicGetDataInstruments();
        return response;
    }

    async fetchDataAssets () {
        const response = await this.publicGetDataAssets();
        return response;
    }

    async fetchDataRates () {
        const response = await this.publicGetDataRates();
        return response;
    }

    async fetchDataCandlesHistory (ticker, resolution, from, to, params = {}) {
        const request = this.extend({ ticker, resolution, from, to }, params);
        const response = await this.publicGetDataCandlesHistorySymbolTickerResolutionResolutionFromFromToTo(request);
        return response;
    }

    async fetchDataDepth (market, params = {}) {
        const request = this.extend({ market }, params);
        const response = await this.publicPostDataDepth(request);
        return response;
    }

    async fetchDataHistory (market, params = {}) {
        const request = this.extend({ market }, params);
        const response = await this.publicPostDataHistory(request);
        return response;
    }

    async fetchExchangeTransactions (market, params = {}) {
        const request = this.extend( { market }, params);
        const response = await this.privatePostExchangeTransactions(request);
        return response;
    }

    async fetchOrders (market, since, limit, params = {}) {
        const request = this.extend({ market }, params);
        const response = await this.privatePostExchangeOrder(request);
        return response;
    }

    async createOrder (market, type, side, amount, price, params = {}) {
        const request = this.extend({
            market,
            amount,
            price,
            side,
            type
        }, params);
        for( let param in request ){
          if(request[params] === null){
            delete request[params]
          }
        }
        const response = await this.privatePutExchangeOrder(request);
        return response;
    }

    async cancelOrder (id, market) {
        const response = await this.privateDeleteExchangeOrderMarketId({ id, market });
        return response;
    }

    async fetchUserLimits () {
        const response = await this.privateGetUserLimits();
        return response;
    }

    async fetchUserType () {
        const response = await this.privateGetUserType();
        return response;
    }

    async fetchUserBalance () {
        const response = await this.privateGetUserBalance();
        return response;
    }

    async fetchDepositAddress (asset, params = {}) {
        const request = this.extend({ asset }, params);
        const response = await this.privatePostWalletDepositAddress(request);
        return response;
    }

    async createWithdrawalRequest (asset, amount, address, params = {}) {
        const request = this.extend({ asset, amount, address }, params);
        const response = await this.privatePutWalletWithdrawal(request);
        return response;
    }

    async fetchWalletData (action, params = {}) {
        const request = this.extend({ action }, params);
        const response = await this.privatePostWalletData(request);
        return response;
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = {}, body) {
        let url = `${this.urls.api}/${path}`;
        if (/{.*}/.test(url)) {
            url = `${this.urls.api}/${this.url(path, params)}`;
        }
        if (['POST', 'PUT'].includes(method)) {
            if (Object.keys(params).length) {
                body = this.json(params);
                headers['Content-Type'] = 'application/json';
            }
        }
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }
        return { url, method, body, headers };
    }
};
