import { Dcomm, BinTools, BN, Buffer } from "dcomm/dist"
import {
  EVMAPI,
  EVMOutput,
  ImportTx,
  TransferableInput,
  KeyChain,
  UTXO,
  UTXOSet,
  SECPTransferInput,
  AmountOutput,
  UnsignedTx,
  Tx
} from "dcomm/dist/apis/evm"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  Defaults
} 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 actchain: EVMAPI = dcomm.ACTChain()
const bintools: BinTools = BinTools.getInstance()
const cKeychain: KeyChain = actchain.keyChain()
const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC"
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
cKeychain.importKey(privKey)
const cAddresses: Buffer[] = actchain.keyChain().getAddresses()
const cAddressStrings: string[] = actchain.keyChain().getAddressStrings()
const actChainBlockchainIdStr: string =
  Defaults.network[networkID].ACT.blockchainID
const actChainBlockchainIdBuf: Buffer = bintools.cb58Decode(
  actChainBlockchainIdStr
)
const astChainBlockchainIdStr: string =
  Defaults.network[networkID].AST.blockchainID
const astChainBlockchainIdBuf: Buffer = bintools.cb58Decode(
  astChainBlockchainIdStr
)
const importedIns: TransferableInput[] = []
const evmOutputs: EVMOutput[] = []
const fee: BN = actchain.getDefaultTxFee()

const main = async (): Promise<any> => {
  const u: any = await actchain.getUTXOs(cAddressStrings[0], "AST")
  const utxoSet: UTXOSet = u.utxos
  const utxos: UTXO[] = utxoSet.getAllUTXOs()
  utxos.forEach((utxo: UTXO) => {
    const assetID: Buffer = utxo.getAssetID()
    const txid: Buffer = utxo.getTxID()
    const outputidx: Buffer = utxo.getOutputIdx()
    const output: AmountOutput = utxo.getOutput() as AmountOutput
    const amt: BN = output.getAmount().clone()
    const input: SECPTransferInput = new SECPTransferInput(amt)
    input.addSignatureIdx(0, cAddresses[0])
    const xferin: TransferableInput = new TransferableInput(
      txid,
      outputidx,
      assetID,
      input
    )
    importedIns.push(xferin)

    const evmOutput: EVMOutput = new EVMOutput(
      cHexAddress,
      amt.sub(fee),
      assetID
    )
    evmOutputs.push(evmOutput)
  })

  const importTx: ImportTx = new ImportTx(
    networkID,
    actChainBlockchainIdBuf,
    astChainBlockchainIdBuf,
    importedIns,
    evmOutputs
  )

  const unsignedTx: UnsignedTx = new UnsignedTx(importTx)
  const tx: Tx = unsignedTx.sign(cKeychain)
  const txid: string = await actchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
