import createHash from "create-hash"
import { Dcomm, BinTools, BN, Buffer } from "dcomm/dist"
import {
  DVMAPI,
  KeyChain,
  SECPTransferOutput,
  SECPTransferInput,
  TransferableOutput,
  TransferableInput,
  UTXOSet,
  UTXO,
  AmountOutput,
  UnsignedTx,
  Tx,
  BaseTx
} from "dcomm/dist/apis/dvm"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  Defaults
} from "dcomm/dist/utils"

const bintools: BinTools = BinTools.getInstance()
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 dcmAssetIDBuf: Buffer = bintools.cb58Decode(dcmAssetID)
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 xAddresses: Buffer[] = astchain.keyChain().getAddresses()
const xAddressStrings: string[] = astchain.keyChain().getAddressStrings()
const outputs: TransferableOutput[] = []
const inputs: TransferableInput[] = []
const fee: BN = astchain.getDefaultTxFee()
const threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from("DVM manual BaseTx to send DCM")
// Uncomment for codecID 00 01
// const codecID: number = 1

const main = async (): Promise<any> => {
  const getBalanceResponse: any = await astchain.getBalance(
    xAddressStrings[0],
    dcmAssetID
  )
  const balance: BN = new BN(getBalanceResponse.balance)
  const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput(
    balance.sub(fee),
    xAddresses,
    locktime,
    threshold
  )
  // Uncomment for codecID 00 01
  // secpTransferOutput.setCodecID(codecID)
  const transferableOutput: TransferableOutput = new TransferableOutput(
    dcmAssetIDBuf,
    secpTransferOutput
  )
  outputs.push(transferableOutput)

  const dvmUTXOResponse: any = await astchain.getUTXOs(xAddressStrings)
  const utxoSet: UTXOSet = dvmUTXOResponse.utxos
  const utxos: UTXO[] = utxoSet.getAllUTXOs()
  utxos.forEach((utxo: UTXO) => {
    const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput
    const amt: BN = amountOutput.getAmount().clone()
    const txid: Buffer = utxo.getTxID()
    const outputidx: Buffer = utxo.getOutputIdx()

    const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt)
    // Uncomment for codecID 00 01
    // secpTransferInput.setCodecID(codecID)
    secpTransferInput.addSignatureIdx(0, xAddresses[0])

    const input: TransferableInput = new TransferableInput(
      txid,
      outputidx,
      dcmAssetIDBuf,
      secpTransferInput
    )
    inputs.push(input)
  })

  const baseTx: BaseTx = new BaseTx(
    networkID,
    bintools.cb58Decode(xBlockchainID),
    outputs,
    inputs,
    memo
  )
  // Uncomment for codecID 00 01
  // baseTx.setCodecID(codecID)
  const unsignedTx: UnsignedTx = new UnsignedTx(baseTx)
  const tx: Tx = unsignedTx.sign(xKeychain)
  const txBuf: Buffer = tx.toBuffer()

  // Start example script for generating the TxID in
  // advance of issuing the tx to a full node

  // Create sha256 hash of the tx buffer
  const sha256Hash: Buffer = Buffer.from(
    createHash("sha256").update(txBuf).digest().buffer
  )

  // cb58 the sha256 hash
  const generatedTxID: string = bintools.cb58Encode(sha256Hash)
  console.log(`Generated TXID: ${generatedTxID}`)

  // End example script for generating the TxID in
  // advance of issuing the tx to a full node

  // get the actual txID from the full node
  const actualTxID: string = await astchain.issueTx(tx)
  console.log(`Success! TXID: ${actualTxID}`)
}

main()
