const { HDPrivateKey, PrivateKey } = 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, request } = require('./rpc')
const path = require('path')
const jq = require('node-jq')
const { consoleJSON } = require('./console')
const console = require('./console')
module.exports = {
  send: function(address, amount, asset, data, type, gasLimit, feeValue, feeType) {

    if (!address) {
      console.warn('please specify the destination address')
      return
    }

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

    let totalAmount = amount
    if (feeType == asset) {
      totalAmount += feeValue
    }

    let accounts = storage.getAccount()
    let addresses = [];
    accounts.forEach(a => {
      addresses.push(a.address)
    })
    return new Promise((resolve, reject) => {
      rpc.getUtxoByAddress({
        addresses: addresses,
        asset: asset
      }).then(res => {

        let total = 0
        let inputs = []
        let keys = []

        res.forEach(u => {
          let sataoshi = u.amount
          if (total < totalAmount) {
            total += sataoshi
            u.amount = sataoshi.toString()
            inputs.push(u)
            accounts.forEach(a => {
              if (a.address == u.address) {
                keys.push(a.pk)
              }
            })
          }
        })

        if (!inputs.length || total < totalAmount) {
          console.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 - totalAmount).toString(),
            assets: asset,
            data: data,
            contractType: type
          })
        }

        if (feeType != asset) {

          rpc.getUtxoByAddress({
            addresses: addresses,
            asset: feeType
          }).then(res => {
            let total = 0

            res.forEach(u => {
              let sataoshi = u.amount
              if (total < feeValue) {
                total += sataoshi
                u.amount = sataoshi.toString()
                inputs.push(u)
                accounts.forEach(a => {
                  if (a.address == u.address) {
                    keys.push(a.pk)
                  }
                })
              }
            })

            if (!inputs.length || total < feeValue) {
              console.warn('not enough utxo as fee')
              reject('not enough utxo as fee')
            }

            outputs.push({
              address: inputs[0].address,
              amount: (total - feeValue).toString(),
              assets: feeType,
              data: "",
              contractType: ""
            })

            let tx = new Transaction({
              inputs: inputs,
              outputs: outputs,
              gasLimit: gasLimit
            })
            let rawTx = tx.sign(keys).toHex()
            rpc.sendRawTransaction(rawTx).then(res => {
              resolve(res)
            }).catch(e => {
              reject(e)
            })

          })


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

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

          rpc.sendRawTransaction(rawTx).then(res => {
            resolve(res)
          }).catch(e => {
            reject(e)
          })
        }
      }).catch(e => {
        console.error(e)
      })
    })
  },
  detail: function(txId) {
    request('getRawTransaction', [txId, true, true]).then(res => {
      console.success('success!')
      consoleJSON(res)
    }).catch(e => {
      console.error(e)
    })

  }
}
