import { Dcomm, BN, Buffer } from "dcomm/dist"
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 athchain: AuthorityVMAPI = dcomm.ATHChain()
const pKeychain: KeyChain = athchain.keyChain()
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
pKeychain.importKey(privKey)
const pAddressStrings: string[] = athchain.keyChain().getAddressStrings()
const astChainBlockchainID: string =
  Defaults.network[networkID].AST.blockchainID
const athChainBlockchainID: string =
  Defaults.network[networkID].ATH.blockchainID
const threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
  "AuthorityVM utility method buildImportTx to import DCM to the ATH-Chain from the AST-Chain"
)
const asOf: BN = UnixNow()

const main = async (): Promise<any> => {
  const authorityVMUTXOResponse: any = await athchain.getUTXOs(
    pAddressStrings,
    athChainBlockchainID
  )
  const utxoSet: UTXOSet = authorityVMUTXOResponse.utxos
  const unsignedTx: UnsignedTx = await athchain.buildImportTx(
    utxoSet,
    pAddressStrings,
    astChainBlockchainID,
    pAddressStrings,
    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()
