"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const jws = __importStar(require("jws"));
const crypto = __importStar(require("crypto"));
const debug = require('debug')('JWT');
class SetlJWT {
    /**
     *
     * @param hostname
     * @param apikey
     * @param userId
     */
    constructor(hostname, stateService, connectionService) {
        this.hostname = hostname;
        this.stateService = stateService;
        this.connectionService = connectionService;
    }
    /**
     * Get Token
     */
    getToken() {
        return __awaiter(this, void 0, void 0, function* () {
            debug('[JWT] Getting Token!');
            const payload = {
                token: '',
                requestid: this.randomString(),
                messagetype: 'initialise',
                timestamp: Math.floor(new Date().getTime() / 1000),
                messagebody: {
                    userid: this.stateService.userId,
                },
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response) {
                this.token = response.token;
                debug('[JWT] Got Token', response.payload);
            }
            else {
                debug('[JWT] No Token Found');
            }
        });
    }
    /**
     *
     * @param JWS
     */
    callWalletNode(JWS) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.stateService.detected) {
                yield this.connectionService.detect(this.stateService.endpoint);
            }
            const node = this.stateService.detectResults.wnRest;
            return new Promise((resolve, reject) => {
                const url = `${node.scheme}://${this.hostname}:${node.port}${node.path}`;
                axios_1.default.post(url, { jws: JWS }, { timeout: 15000 }).then((res) => {
                    debug(res.data.jws);
                    const valid = this.verifyJws(res.data.jws, this.stateService.apiKey);
                    if (valid) {
                        const json = this.parseJws(res.data.jws);
                        resolve(json);
                    }
                    else {
                        debug('[JWT] Error - Cannot verify JWS');
                        debug(JSON.stringify(this.parseJws(res.data.jws)));
                    }
                }).catch(function (error) {
                    // handle error
                    let json;
                    try {
                        json = this.parseJws(error.response.data.jws);
                    }
                    catch (e) {
                        json = 'Internal Error';
                    }
                    debug('[JWT] Error Code: ', error.response.status);
                    debug('[JWT] Error Reason: ', json);
                });
            });
        });
    }
    /**
     *
     * @param JWS
     */
    callMemberNode(JWS) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.stateService.detected) {
                yield this.connectionService.detect(this.stateService.endpoint);
            }
            return new Promise((resolve, reject) => {
                const node = this.stateService.detectResults.mnRest;
                axios_1.default.post(`${node.scheme}://${this.hostname}:${node.port}${node.path}`, { jws: JWS }, {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                }).then((res) => {
                    debug(res.data.jws);
                    const valid = this.verifyJws(res.data.jws, this.stateService.apiKey);
                    if (valid) {
                        const json = this.parseJws(res.data.jws);
                        resolve(json);
                    }
                    else {
                        debug('[JWT] Error - Cannot verify JWS');
                        debug(JSON.stringify(this.parseJws(res.data.jws)));
                    }
                }).catch(function (error) {
                    // handle error
                    let json;
                    try {
                        json = this.parseJws(error.response.data.jws);
                    }
                    catch (e) {
                        json = 'Internal Error';
                    }
                    debug(error);
                    debug('[JWT] Error Code: ', error.response.status);
                    debug('[JWT] Error Reason: ', json);
                });
            });
        });
    }
    /**
     *
     * @param MsgRequest
     * @param apiKey
     */
    getJwsHs256(MsgRequest) {
        return jws.sign({
            header: { alg: 'HS256', typ: 'JWT' },
            payload: MsgRequest,
            secret: this.stateService.apiKey,
        });
    }
    /**
     *
     * @param thisJWS
     * @param apiKey
     */
    parseJws(thisJWS) {
        const JWS = jws.decode(thisJWS);
        if (JWS !== null && typeof JWS.payload === 'object') {
            debug('Dont parse JSON', JWS);
            return JWS.payload;
        }
        return JSON.parse(JWS.payload);
    }
    /**
     *
     * @param thisJWS
     * @param thisSecret
     */
    verifyJws(thisJWS, thisSecret) {
        const parts = thisJWS.split('.');
        let JWS = false;
        if (parts.length === 3) {
            JWS = jws.verify(thisJWS, 'HS256', thisSecret);
        }
        return JWS;
    }
    /**
     *
     */
    addDefaultPayloads() {
        return {
            token: this.stateService.token,
            requestid: this.randomString(),
            timestamp: Math.floor(new Date().getTime() / 1000),
        };
    }
    /**
     * Generate Random String for Request ID
     *
     * @param size
     */
    randomString(size = 16) {
        return crypto.randomBytes(size).toString('base64').slice(0, size);
    }
    /**
     * Call to Membernode / WalletNode
     *
     * @param payloadIn - object to send
     * @param requestType - {request,tx} switches between request and tx, default is request
     * @param endpoint - {wallet,member} switches between walletnode for member, default is wallet
     */
    call(payloadIn, requestType, endpoint) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = requestType;
            payload['messagebody'] = payloadIn;
            const data = this.getJwsHs256(payload);
            let response;
            if (endpoint === 'member') {
                response = yield this.callMemberNode(data).catch(err => debug(`[JWT] Get Status Error: ${err}`));
            }
            else {
                response = yield this.callWalletNode(data).catch(err => debug(`[JWT] Get Status Error: ${err}`));
            }
            if (response.status === 'OK') {
                return response;
            }
            return false;
        });
    }
    /********************************************************

    All detailed calls below here currently not exposed but would work

    *******************************************************/
    getStatus() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'state',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(`Get Status Error: ${err}`));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getMyUserDetails() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'gud',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getEncumber() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'encumbrancedetails',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getMyWalletList() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'gmywa',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    newUser(account, username, email, userType, password) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'nu',
                account,
                username,
                email,
                userType,
                password,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    newWallet(walletName, account, walletType) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'nw',
                walletName,
                account,
                walletType,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateUserWalletPermissions(userId, toAdd, toUpdate, toDelete) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'udwp',
                userid: userId,
                toAdd,
                toUpdate,
                toDelete,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    allGetDetails() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'allgetdetails',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getMyFundAccess() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getfundaccessmy',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getMergers() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getmerger',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getWalletDirectory() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'gud',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getWalletIDByAddr(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'gwidbya',
                address,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getCoupons() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getcoupon',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateCoupon(couponID, status, amount, amountGross) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updatecoupon',
                couponID,
                amount,
                amountGross,
                status,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateFundStatus(status, issuer, shareName) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updatefundsharestatus',
                issuer,
                shareName,
                status,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getSplits() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getsplit',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getOrders(dateOrder) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getorders',
                dateOrder,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getOrdersFunds(orderId) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getordersfunds',
                orderID: orderId,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateSplit(splitID, status, factor) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updatesplit',
                splitID,
                factor,
                status,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getMyWalletAccess() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getmywalletaccess',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'retry') {
                return this.getMyWalletAccess;
            }
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getContractsByWallet(walletID) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'contract',
                walletid: walletID,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            debug('GET CONTRACTS-------', response);
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getWalletAddresses(walletId) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'addresses',
                walletid: walletId,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    walletCommitToContract(walletID, data) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'tx';
            payload['messagebody'] = {
                topic: 'cocom',
                walletid: parseInt(walletID),
                address: data['commitaddress'],
                function: data['function'],
                contractdata: data['contractdata'],
                contractaddress: data['contractaddress'],
            };
            const dataa = this.getJwsHs256(payload);
            debug('DATA', dataa);
            const response = yield this.callWalletNode(dataa).catch(err => debug(err));
            debug('Commit', response);
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getUserIssuedList() {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getuserissuedlist',
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    voidAsset(walletID, namespace, instrument, fromAddr, toAddr, amount) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'tx';
            payload['messagebody'] = {
                topic: 'istra',
                walletid: walletID,
                namespace,
                instrument,
                fromaddress: fromAddr,
                toaddress: toAddr,
                amount,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    issueAsset(walletID, namespace, instrument, toAddr, amount) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'tx';
            payload['messagebody'] = {
                topic: 'asiss',
                walletid: walletID,
                namespace,
                instrument,
                toaddress: toAddr,
                amount,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getIssuedAssetBalance(walletID, data) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'holders',
                walletid: walletID,
                namespace: data['issuer'],
                classid: data['instrument'],
            };
            const dataa = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(dataa).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getIndexRate(indexID, startDate, endDate) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getindexrate',
                indexid: indexID,
                fromdate: startDate,
                todate: endDate,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getWalletHoldings(walletID) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'holdingsdetail',
                walletid: walletID,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    exenc(walletID, issuer, instrument, toAddr, fromAddr, amount) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'tx';
            payload['messagebody'] = {
                topic: 'exenc',
                walletid: walletID,
                namespace: issuer,
                instrument,
                // 'toaddress':toAddr,
                //
                amount,
                address: toAddr,
                subjectaddress: fromAddr,
                paymentaddress: toAddr,
                reference: 'ref',
            };
            // "messagebody": {
            //     "txtype": "exenc",
            //     "walletid": <int>, # Wallet ID.
            //     "reference": <string>, # Unique (to this Address) reference for the
            //     Encumbrance.
            //     "address": <string>, # Address authoring the request. May be a
            //     Beneficiary or Administrator address.
            //     "subjectaddress": <string>, # Specify address to remove Encumbrance from
            //     "tochainid": <int>, # Optional. May be specified if transfering
            //     asset to a linked Blockchain
            //     "paymentaddress": <string>, # Specify address to remove Encumbrance from
            //     "namespace": <string>, # Namespace of this asset class. Of course,
            //     the namespace must be controlled by an
            //     address in the indicated wallet.
            //     "instrument": <string>, # Asset class Identifier.
            //     "amount": <int>, # Amount of asset to unencumber
            //     "protocol": <string>, # Optional tag.
            //     "metadata": <string> # Optional tag.
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getWalletInstruments(walletID) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'request';
            payload['messagebody'] = {
                topic: 'instruments',
                walletid: walletID,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getOrderByAddr(address, orderID) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getorderbyaddr',
                address,
                orderID,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateOrderStatus(orderID, status, contractAddress) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updateorders',
                orderID,
                status,
                contractAddress,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getArrangementByContractAddr(walletID, contractAddress) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'gacbc',
                walletid: walletID,
                contractAddress,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    getAssetPrice(asset, navDate, status, pageNum, pageSize) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'getnavlist',
                fundname: asset,
                navdate: navDate,
                status,
                pagenum: pageNum,
                pageSize,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    splitAsset(walletID, namespace, instrument, ratio) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'caspl',
                walletID,
                namespace,
                instrument,
                ratio,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    newContract(walletID, address, contractData) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'tx';
            payload['messagebody'] = {
                topic: 'conew',
                walletid: walletID,
                address,
                function: 'dvp_uk',
                contractdata: contractData,
            };
            const data = this.getJwsHs256(payload);
            debug('NEW Contract:', data);
            const response = yield this.callWalletNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                debug(response['payload']);
                return response['payload'];
            }
            return false;
        });
    }
    saveArrangement(walletID, type, metaData, quantity, parties, cutoff, delivery, valuation, asset) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                creatorId: walletID,
                type,
                metaData,
                asset,
                investBy: 0,
                quantity,
                amountWithCost: 0,
                feePercent: 0,
                platFormFee: 0,
                parties,
                cutoff,
                delivery,
                valuation,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    addArrangementContractMap(walletID, arrangementID, contractAddress, expiry) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'aacm',
                walletID,
                arrangementID,
                contractAddress,
                expiry,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateNav(asset, navDate, status, price) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updatenav',
                fundname: asset,
                funddate: navDate,
                pricestatus: status,
                price,
                force: 1,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateArrangement(walletID, arrangementID, status, price) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updatearrangement',
                walletID,
                arrangementID,
                status,
                price,
                deamonToken: 1,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    updateMerger(mergerID, status, fundOldNav, fundNewNav) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updatemerger',
                mergerID,
                fundOldNav,
                fundNewNav,
                status,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    sendMail(subject, body, walletID, walletPubkey, recipients, useComm = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const uniqueLEI = [];
            let uniqueRecipients = {};
            if (!useComm) {
                const recipientsAddr = this.array_keys(recipients);
                const allWalletId = yield this.getWalletIDByManyAddresses(recipientsAddr);
                debug('allWalletId', allWalletId.data);
                debug('allWalletID size', allWalletId.data.length);
                // tslint:disable-next-line
                for (let i = 0; i < allWalletId.data.length; i++) {
                    const thisWalletLeiID = allWalletId.data[i].leiID;
                    if (!(uniqueLEI.indexOf(thisWalletLeiID) > -1)) {
                        uniqueLEI.push(thisWalletLeiID);
                        uniqueRecipients[recipientsAddr[i]] = 0;
                    }
                }
            }
            else {
                uniqueRecipients = recipients;
            }
            const subject64 = Buffer.from(subject).toString('base64');
            const body64 = {
                action: {
                    type: '',
                },
                general: Buffer.from(body).toString('base64'),
            };
            debug('uniqueRecipients1', uniqueRecipients);
            // Send Mail
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'email_send',
                mailSubject: subject64,
                mailBody: JSON.stringify(body64),
                senderId: walletID,
                senderPub: walletPubkey,
                recipients: uniqueRecipients,
                parentId: 0,
                arrangementId: 0,
                arrangementStatus: 0,
                attachment: 0,
                hasAction: 0,
                isDraft: 0,
            };
            debug('payload', payload);
            const data = this.getJwsHs256(payload);
            debug('DATA:', data);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    array_keys(myObject) {
        const output = [];
        for (const key in myObject) {
            output.push(key);
        }
        return output;
    }
    getWalletIDByManyAddresses(addresses) {
        return __awaiter(this, void 0, void 0, function* () {
            debug('add', addresses);
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'gwidbyma',
                addresses,
            };
            const data = this.getJwsHs256(payload);
            const response = yield this.callMemberNode(data).catch(err => debug(err));
            debug('response', response);
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
    unEncumberTx(walletID, data) {
        return __awaiter(this, void 0, void 0, function* () {
            const payload = this.addDefaultPayloads();
            payload['messagetype'] = 'db';
            payload['messagebody'] = {
                topic: 'updatearrangement',
                walletID,
                reference: data['reference'],
                address: data['address'],
                subjectaddress: data['subjectAddr'],
                namespace: data['namespace'],
                instrument: data['instrument'],
                amount: data['amount'],
            };
            const dataa = this.getJwsHs256(payload);
            const response = yield this.callWalletNode(dataa).catch(err => debug(err));
            if (response['payload'].status === 'OK') {
                return response['payload'];
            }
            return false;
        });
    }
}
exports.SetlJWT = SetlJWT;
