import { Dcomm, BN, Buffer } from "dcomm/dist"
import { DVMAPI, KeyChain, UTXOSet, UnsignedTx, Tx } from "dcomm/dist/apis/dvm"
import {
  GetBalanceResponse,
  GetUTXOsResponse
} from "dcomm/dist/apis/dvm/interfaces"
import { Defaults } from "dcomm/dist/utils"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  UnixNow
} from "dcomm/dist/utils"

const ip: string = "localhost"
const port: number = 9650
const protocol: string = "http"
const networkID: number = 1337
const xBlockchainID: string = Defaults.network[networkID].AST.blockchainID
const dcmAssetID: string = Defaults.network[networkID].AST.dcmAssetID
const dcomm: Dcomm = new Dcomm(ip, port, protocol, networkID, xBlockchainID)
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 asOf: BN = UnixNow()
const threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from("DVM utility method buildBaseTx to send DCM")
const fee: BN = astchain.getDefaultTxFee()

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

  const unsignedTx: UnsignedTx = await astchain.buildBaseTx(
    utxoSet,
    amount,
    dcmAssetID,
    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()
