const { HDPrivateKey, PrivateKey } = require('bitcore-lib')
const { Address } = require('@asimovdev/asimovjs')
const readlineSync = require('readline-sync')
const colors = require('colors')
const storage = require('./storage')
const { request } = require('./rpc')
module.exports = {
  createAccount: function(pk) {
    if (!pk) {
      pk = readlineSync.question(colors.green('input private key:'))
      if (!pk) {
        return
      }

    }
    pk = pk.replace('0x', '')
    let accounts = storage.getAccount()
    let isExist = false
    accounts.forEach(p => {
      if (p.pk == pk) {
        isExist = true

        return
      }
    });

    if (isExist) {
      console.log(colors.yellow('the private key is already existed!'))
      return
    }

    let hdKey = new PrivateKey(pk)
    let address = new Address(hdKey.publicKey).toString()
    let pair = {
      address: address,
      pk: pk
    }
    console.log(colors.green('success!'))
    console.log(colors.green('account address: ') + address)

    accounts.push(pair)

    storage.setAccount(accounts)
  },
  listAccount: function() {
    let accounts = storage.getAccount()
    accounts.forEach(a => {
      console.log(colors.green(a.address))
    })
  },
  balance: function() {
    let accounts = storage.getAccount()
    let addresses = [];
    accounts.forEach(a => {
      addresses.push(a.address)
    })
    request('getBalances', [addresses]).then(res => {

      res.forEach(b => {
        console.log(" ")
        console.log(colors.green(b.address))
        b.assets.forEach(a => {
          console.log('    ' + colors.green(a.asset) + ':' + colors.yellow(a.value))
        })
      })
    })
  },
  utxo: function() {
    let accounts = storage.getAccount()
    let addresses = [];
    accounts.forEach(a => {
      addresses.push(a.address)
    })
    request('getUtxoByAddress', [addresses, ""]).then(res => {
      res.forEach((u, idx) => {
        console.log(" ")
        console.log(colors.yellow('  index:  ') + colors.green(idx))
        console.log(colors.yellow('  address:  ') + colors.green(u.address))
        console.log(colors.yellow('  txid:  ') + colors.green(u.txid))
        console.log(colors.yellow('  vout:  ') + colors.green(u.vout))
        console.log(colors.yellow('  asset:  ') + colors.green(u.assets))
        console.log(colors.yellow('  amount:  ') + colors.green(u.amount))
      })

    })

  },
  use: function() {
    let accounts = storage.getAccount()
    let addresses = [];
    accounts.forEach(a => {
      addresses.push(a.address)
    })
    let index = readlineSync.keyInSelect(addresses, 'choose the account to set as default')

    storage.setMainAccount(accounts[index])
    console.log(colors.green('success!'))

  },
  getMainAccount:function(){
   return  storage.getMainAccount()
  }
}
