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 {
  Defaults,
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey
} 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 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 blockchainID: string = Defaults.network[networkID].AST.blockchainID
const dcmAssetID: string = Defaults.network[networkID].AST.dcmAssetID
const dcmAssetIDBuf: Buffer = bintools.cb58Decode(dcmAssetID)
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 and ANT")
// Uncomment for codecID 00 01
// const codecID: number = 1

const main = async (): Promise<any> => {
  const dvmUTXOResponse: any = await astchain.getUTXOs(xAddressStrings)
  const utxoSet: UTXOSet = dvmUTXOResponse.utxos
  const utxos: UTXO[] = utxoSet.getAllUTXOs()
  utxos.forEach((utxo: UTXO): void => {
    const typeID: number = utxo.getOutput().getTypeID()
    if (typeID != 6) {
      const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput
      const amt: BN = amountOutput.getAmount().clone()
      const txID: Buffer = utxo.getTxID()
      const outputIDX: Buffer = utxo.getOutputIdx()
      const assetID: Buffer = utxo.getAssetID()

      if (assetID.toString("hex") === dcmAssetIDBuf.toString("hex")) {
        const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput(
          amt.sub(fee),
          xAddresses,
          locktime,
          threshold
        )
        // Uncomment for codecID 00 01
        // secpTransferOutput.setCodecID(codecID)
        const transferableOutput: TransferableOutput = new TransferableOutput(
          dcmAssetIDBuf,
          secpTransferOutput
        )
        outputs.push(transferableOutput)

        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)
      } else {
        const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput(
          amt,
          xAddresses,
          locktime,
          threshold
        )
        // Uncomment for codecID 00 01
        // secpTransferOutput.setCodecID(codecID)
        const transferableOutput: TransferableOutput = new TransferableOutput(
          assetID,
          secpTransferOutput
        )
        outputs.push(transferableOutput)

        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,
          assetID,
          secpTransferInput
        )
        inputs.push(input)
      }
    }
  })

  const baseTx: BaseTx = new BaseTx(
    networkID,
    bintools.cb58Decode(blockchainID),
    outputs,
    inputs,
    memo
  )
  // Uncomment for codecID 00 01
  // baseTx.setCodecID(codecID)
  const unsignedTx: UnsignedTx = new UnsignedTx(baseTx)
  const tx: Tx = unsignedTx.sign(xKeychain)
  const txid: string = await astchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
