import { Dcomm, BinTools, BN, Buffer } from "dcomm/dist"
import {
  DVMAPI,
  KeyChain,
  UTXOSet,
  UnsignedTx,
  Tx,
  SECPMintOutput,
  DVMConstants,
  SECPTransferOutput,
  UTXO
} from "dcomm/dist/apis/dvm"
import { GetUTXOsResponse } from "dcomm/dist/apis/dvm/interfaces"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  UnixNow
} from "dcomm/dist/utils"

// assetID is generated from running
// ts-node examples/dvm/buildCreateAssetTx.ts
// if you run the dvm.getAllBalances method you will see the asset alongside DCM, and a balance of 507

const getUTXOIDs = (
  utxoSet: UTXOSet,
  txid: string,
  outputType: number = DVMConstants.SECPXFEROUTPUTID_CODECONE,
  assetID = "Ycg5QzddNwe3ebfFXhoGUDnWgC6GE88QRakRnn9dp3nGwqCwD"
): string[] => {
  const utxoids: string[] = utxoSet.getUTXOIDs()
  let result: string[] = []
  for (let index: number = 0; index < utxoids.length; ++index) {
    if (
      utxoids[index].indexOf(txid.slice(0, 10)) != -1 &&
      utxoSet.getUTXO(utxoids[index]).getOutput().getOutputID() == outputType &&
      assetID ==
        bintools.cb58Encode(utxoSet.getUTXO(utxoids[index]).getAssetID())
    ) {
      result.push(utxoids[index])
    }
  }
  return result
}

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 bintools: BinTools = BinTools.getInstance()
const xKeychain: KeyChain = astchain.keyChain()
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
xKeychain.importKey(privKey)
const xAddresses: Buffer[] = astchain.keyChain().getAddresses()
const xAddressStrings: string[] = astchain.keyChain().getAddressStrings()
const threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
  "DVM utility method buildSECPMintTx to mint an ANT"
)
const asOf: BN = UnixNow()

const main = async (): Promise<any> => {
  const dvmUTXOResponse: GetUTXOsResponse = await astchain.getUTXOs(
    xAddressStrings
  )
  const utxoSet: UTXOSet = dvmUTXOResponse.utxos
  const utxos: UTXO[] = utxoSet.getAllUTXOs()
  let mintUTXOID: string = ""
  let mintOwner: SECPMintOutput = new SECPMintOutput()
  let secpTransferOutput: SECPTransferOutput = new SECPTransferOutput()
  let txid: Buffer = Buffer.from("")
  let assetID: Buffer = Buffer.from("")
  utxos.forEach((utxo: UTXO) => {
    if (utxo.getOutput().getTypeID() === 6) {
      txid = utxo.getTxID()
      assetID = utxo.getAssetID()
    }
  })
  const secpMintOutputUTXOIDs: string[] = getUTXOIDs(
    utxoSet,
    bintools.cb58Encode(txid),
    DVMConstants.SECPMINTOUTPUTID,
    bintools.cb58Encode(assetID)
  )
  mintUTXOID = secpMintOutputUTXOIDs[0]
  const utxo: UTXO = utxoSet.getUTXO(secpMintOutputUTXOIDs[0])
  mintOwner = utxo.getOutput() as SECPMintOutput
  const amount: BN = new BN(54321)
  secpTransferOutput = new SECPTransferOutput(
    amount,
    xAddresses,
    locktime,
    threshold
  )

  const unsignedTx: UnsignedTx = await astchain.buildSECPMintTx(
    utxoSet,
    mintOwner,
    secpTransferOutput,
    xAddressStrings,
    xAddressStrings,
    mintUTXOID,
    memo,
    asOf
  )

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

main()
