import { Dcomm, BN, Buffer } from "dcomm/dist"
import { DVMAPI, KeyChain, UTXOSet, UnsignedTx, Tx } from "dcomm/dist/apis/dvm"
import { GetUTXOsResponse } from "dcomm/dist/apis/dvm/interfaces"
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 xKeychain: KeyChain = astchain.keyChain()
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
xKeychain.importKey(privKey)
const xAddressStrings: string[] = astchain.keyChain().getAddressStrings()
const athChainBlockchainID: string =
  Defaults.network[networkID].ATH.blockchainID
const threshold: number = 1
const locktime: BN = new BN(0)
const asOf: BN = UnixNow()
const memo: Buffer = Buffer.from(
  "DVM utility method buildImportTx to import DCM to the AST-Chain from the ATH-Chain"
)

const main = async (): Promise<any> => {
  const dvmUTXOResponse: GetUTXOsResponse = await astchain.getUTXOs(
    xAddressStrings,
    athChainBlockchainID
  )
  const utxoSet: UTXOSet = dvmUTXOResponse.utxos

  const unsignedTx: UnsignedTx = await astchain.buildImportTx(
    utxoSet,
    xAddressStrings,
    athChainBlockchainID,
    xAddressStrings,
    xAddressStrings,
    xAddressStrings,
    memo,
    asOf,
    locktime,
    threshold
  )
  const tx: Tx = unsignedTx.sign(xKeychain)
  const txid: string = await astchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
