var router = require('koa-router')();
var moralis = require('../model/moralis_sdk.js')
var utils = require('../model/utils.js');

router.prefix('/sdk');

/**
 * 获取代币价格
 * @param {*} ctx 
 */
async function getAllTotkenPrice(ctx) {
    var ret = await moralis.getAllTotkenPrice()
    console.log('getTotkenPrice result:', ret)
    if (ret)
        ctx.body = utils.toJson(0, ret, null);
    else ctx.body = utils.toJson(-1, null, "redis read error.");
}

/**
 * 获取交易记录
 * @param {*} ctx 
 */
async function getTransfers(ctx) {
    console.log("body", ctx);
    const obj = ctx.request.body;
    console.log("obj", obj);
    if (!obj.chain)//默认 bsc 币安链
        obj.chain = 'bsc'
    await moralis.getTokenTransfers(obj).then((result) => {
        ctx.body = result;
    })
}

/**
 * 出金，入金交易
 * @param {*} ctx 
 * @returns 
 */
async function transfer(ctx) {
    if (ctx.request == null || ctx.request.body == null) {
        ctx.body = utils.toJson(-1, null, "request error. ");
        return
    }
    const obj = ctx.request.body;
    await moralis.transfer(obj).then((result) => {
        ctx.body = result;
    });
}

async function getAllTokenWithdrawInfoLists(ctx) {
    if (ctx.request == null || ctx.request.body == null) {
        ctx.body = utils.toJson(-1, null, "request error. ");
        return
    }
    ctx.body = await moralis.getAllTokenWithdrawInfoLists(ctx);
}

async function withdraw(ctx) {
    if (ctx.request == null || ctx.request.body == null) {
        ctx.body = utils.toJson(-1, null, "request error. ");
        return
    }
    const obj = ctx.request.body;
    await moralis.withdraw(obj).then((result) => {
        ctx.body = result;
    });
}

//获取交易记录
router.post('/getTransfers', getTransfers)
// 获取所有代币价格
router.post('/getAllTotkenPrice', getAllTotkenPrice)
//归集 获取当前余额是否大于 1 美刀，大于就将用户充币地址的余额转移到归集地址
router.post('/transfer', transfer)
//提现
router.post('/withdraw', withdraw);
//获取所有地址的所要消耗的最低提取费
router.post('/getAllTokenWithdrawInfoLists', getAllTokenWithdrawInfoLists)

async function crypto_test(ctx) {
    if (ctx.request == null || ctx.request.body == null) {
        ctx.body = utils.toJson(-1, null, "request error. ");
        return;
    }

    const obj = ctx.request.body;
    var crypt_key = obj.key;
    var message = obj.privateKey;

    //process.env.NODE_ENV
    console.log("NDK_HOME", process.env.NDK_HOME);

    var de_message = utils.decryptPrivityKey(crypt_key, message);

    console.log("decrypt message:", message);

    ctx.body = {
        decrypt: de_message
    }
}
router.post('/crypto_test', crypto_test)

module.exports = router;
