const { HDPrivateKey, PrivateKey, Unit } = require('bitcore-lib')
const { TemplateWarehouse, Compiler, Transaction } = require('@asimovdev/asimovjs')
const readlineSync = require('readline-sync')
const colors = require('colors')
const storage = require('./storage')
const { rpc } = require('./rpc')
const path = require('path');
let Module = require('../lib/flow_4.0.0')
let compiler = new Compiler(Module)
let warehouse = new TemplateWarehouse({
  baseProvider: {
    chainRpcProvider: rpc
  }
})



module.exports = {
  send: function(address, amount, asset, data, type, gasLimit) {

    if (!address) {
      console.log(colors.yellow('please specify the destination address'))
      return
    }

    if (!amount) {
      console.log(colors.yellow('the amount should be larger than 0'))
      return
    }

    let accounts = storage.getAccount()
    let addresses = [];

    accounts.forEach(a => {
      addresses.push(a.address)
    })
    rpc.getUtxoByAddress({
      addresses: addresses,
      asset: asset
    }).then(res => {

      let total = 0
      let inputs = []
      let keys = []
      res.forEach(u => {
        let sataoshi = Unit.fromBTC(u.amount).toSatoshis()
        if (total < amount) {
          total += sataoshi
          u.amount = sataoshi.toString()
          inputs.push(u)
          accounts.forEach(a => {
            if (a.address == u.address) {
              keys.push(a.pk)
            }
          })
        }
      })
      if (!inputs.length) {
        console.log(colors.warn('not enough utxo!'))
        return
      }
      let outputs = [{
        address: address,
        amount: amount.toString(),
        assets: asset,
        data: data,
        contractType: type
      }]

      if (total - amount) {
        outputs.push({
          address: inputs[0].address,
          amount: (total - amount).toString(),
          assets: asset,
          data: data,
          contractType: type
        })
      }

      let tx = new Transaction({
        inputs: inputs,
        outputs: outputs,
        gasLimit: gasLimit
      })

      let rawTx = tx.sign(keys).toHex()

     return rpc.sendRawTransaction(rawTx)
    })

  },
  detail: function(txId) {
    console.log(txId)
    rpc.getRawTransaction({
      txId: txId,
      verbose: true,
      vinExtra: true
    }).then(res => {
      console.log(colors.green('success!'))
      console.log(colors.green(res))

    }).catch(e => {
      console.log(colors.red(e))
    })

  }
}
