const utils = require('ethereumjs-util');
const bip39 = require('bip39');
const HDWallet = require('ethereum-hdwallet')
const Web3 = require('web3.js-thk');
const fs = require('fs');
const web3 = new Web3();

const rpxUrl = "http://rpctest.chainopen.cn"

const init = () => {
    return new Promise(async (resolve, reject) => {
        const {mnemonic} = require("./config.json");
        const seed = await bip39.mnemonicToSeed(mnemonic.trim())
        const hdwallet = HDWallet.fromSeed(seed)
        const privateKey = hdwallet.derive('m/44\'/60\'/0\'/0/0').getPrivateKey()
        const address = utils.privateToAddress(privateKey)
        console.log('Wallet: 0x' + address.toString('hex'))
        web3.setProvider(new web3.providers.HttpProvider(rpxUrl));
        web3.thk.defaultPrivateKey = privateKey
        web3.thk.defaultAddress = '0x' + address.toString('hex').toLowerCase()
        web3.thk.defaultChainId = "1"
        resolve(true)
    })
}
const getTxHash = (transactionHash) => {
    return new Promise(async (resolve, reject) => {
        var i=0;
        do {
            var conresp = web3.thk.GetTransactionByHash(web3.thk.defaultChainId, transactionHash);
            i++;
        } while (conresp.errCode == 4003 && i<20)
        resolve(conresp)
    })
}
const callContract = (abi, contractAddress) => {
    return new Promise(async (resolve, reject) => {
        const contractObj = web3.thk.contract(abi, contractAddress).at(contractAddress);
        resolve(contractObj);
    })
}
const deployContract = (contract, param) => {
    return new Promise(async (resolve, reject) => {
        deploy(contract, param).then((contracts) => {
            console.log('transactionHash: ', contracts.transactionHash)
            getTxHash(contracts.transactionHash).then((Address) => {
                console.log('contract Address: ', Address)
                callContract(contracts.abi, Address).then((Instance) => {
                    resolve(Instance);
                })
            })
        })
    })
}
const setVal = (value) => {
    web3.thk.setVal(ether(value));
}
const ether = (amount) => {
    return web3.toWei(amount);
}
module.exports = { init,  getTxHash, callContract, deployContract, ether, setVal };