import { Dcomm, BN, Buffer } from "dcomm/dist"
import {
  DVMAPI,
  KeyChain as DVMKeyChain,
  UTXOSet,
  UnsignedTx,
  Tx
} from "dcomm/dist/apis/dvm"
import {
  GetBalanceResponse,
  GetUTXOsResponse
} from "dcomm/dist/apis/dvm/interfaces"
import {
  KeyChain as AuthorityVMKeyChain,
  AuthorityVMAPI
} 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: AuthorityVMKeyChain = 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 athChainBlockchainID: string =
  Defaults.network[networkID].ATH.blockchainID
const dcmAssetID: string = Defaults.network[networkID].AST.dcmAssetID
const locktime: BN = new BN(0)
const asOf: BN = UnixNow()
const memo: Buffer = Buffer.from(
  "DVM utility method buildExportTx to export DCM to the ATH-Chain from the AST-Chain"
)
const fee: BN = astchain.getDefaultTxFee()

const main = async (): Promise<any> => {
  const dvmUTXOResponse: GetUTXOsResponse = await astchain.getUTXOs(
    xAddressStrings
  )
  const utxoSet: UTXOSet = dvmUTXOResponse.utxos
  const getBalanceResponse: GetBalanceResponse = await astchain.getBalance(
    xAddressStrings[0],
    dcmAssetID
  )
  const balance: BN = new BN(getBalanceResponse.balance)
  const amount: BN = balance.sub(fee)

  const unsignedTx: UnsignedTx = await astchain.buildExportTx(
    utxoSet,
    amount,
    athChainBlockchainID,
    pAddressStrings,
    xAddressStrings,
    xAddressStrings,
    memo,
    asOf,
    locktime
  )

  const tx: Tx = unsignedTx.sign(xKeychain)
  const txid: string = await astchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
