import { Dcomm, BN, Buffer } from "dcomm/dist"
import {
  AuthorityVMAPI,
  KeyChain,
  UTXOSet,
  UnsignedTx,
  Tx
} from "dcomm/dist/apis/authorityvm"
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 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 threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
  "AuthorityVM utility method buildAddDelegatorTx to add a delegator to the primary subnet"
)
const asOf: BN = UnixNow()
const nodeID: string = "NodeID-DueWyGi3B9jtKfa9mPoecd4YSDJ1ftF69"
const startTime: BN = UnixNow().add(new BN(60 * 1))
const endTime: BN = startTime.add(new BN(2630000))

const main = async (): Promise<any> => {
  const stakeAmount: any = await athchain.getMinStake()
  const authorityVMUTXOResponse: any = await athchain.getUTXOs(pAddressStrings)
  const utxoSet: UTXOSet = authorityVMUTXOResponse.utxos

  const unsignedTx: UnsignedTx = await athchain.buildAddDelegatorTx(
    utxoSet,
    pAddressStrings,
    pAddressStrings,
    pAddressStrings,
    nodeID,
    startTime,
    endTime,
    stakeAmount.minDelegatorStake,
    pAddressStrings,
    locktime,
    threshold,
    memo,
    asOf
  )

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

main()
