import { Dcomm, BN, Buffer } from "dcomm/dist"
import { DVMAPI, KeyChain as DVMKeyChain } from "dcomm/dist/apis/dvm"
import {
  AuthorityVMAPI,
  KeyChain,
  UTXOSet,
  UnsignedTx,
  Tx
} from "dcomm/dist/apis/authorityvm"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  Defaults,
  UnixNow
} from "dcomm/dist/utils"

const ip: string = "localhost"
const port: number = 9650
const protocol: string = "http"
const networkID: number = 1337
const dcomm: Dcomm = new Dcomm(ip, port, protocol, networkID)
const astchain: DVMAPI = dcomm.ASTChain()
const athchain: AuthorityVMAPI = dcomm.ATHChain()
const xKeychain: DVMKeyChain = astchain.keyChain()
const pKeychain: KeyChain = athchain.keyChain()
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
xKeychain.importKey(privKey)
pKeychain.importKey(privKey)
const xAddressStrings: string[] = astchain.keyChain().getAddressStrings()
const pAddressStrings: string[] = athchain.keyChain().getAddressStrings()
const actChainBlockchainID: string =
  Defaults.network[networkID].ACT.blockchainID
const fee: BN = athchain.getDefaultTxFee()
const threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
  "AuthorityVM utility method buildExportTx to export DCM from the ATH-Chain to the ACT-Chain"
)
const asOf: BN = UnixNow()

const main = async (): Promise<any> => {
  const getBalanceResponse: any = await athchain.getBalance(pAddressStrings[0])
  const unlocked: BN = new BN(getBalanceResponse.unlocked)
  const authorityVMUTXOResponse: any = await athchain.getUTXOs(pAddressStrings)
  const utxoSet: UTXOSet = authorityVMUTXOResponse.utxos
  const unsignedTx: UnsignedTx = await athchain.buildExportTx(
    utxoSet,
    unlocked.sub(fee),
    actChainBlockchainID,
    xAddressStrings,
    pAddressStrings,
    pAddressStrings,
    memo,
    asOf,
    locktime,
    threshold
  )
  const tx: Tx = unsignedTx.sign(pKeychain)
  const txid: string = await athchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
