import { Dcomm, BinTools, BN, Buffer } from "dcomm/dist"
import { DVMAPI, KeyChain as DVMKeyChain } from "dcomm/dist/apis/dvm"
import {
  AuthorityVMAPI,
  KeyChain,
  SECPTransferOutput,
  SECPTransferInput,
  TransferableOutput,
  TransferableInput,
  UTXOSet,
  UTXO,
  AmountOutput,
  UnsignedTx,
  Tx,
  ExportTx
} from "dcomm/dist/apis/authorityvm"
import { Output } from "dcomm/dist/common"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  Defaults,
  MILLIDCM
} 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 athchain: AuthorityVMAPI = dcomm.ATHChain()
const bintools: BinTools = BinTools.getInstance()
const xKeychain: DVMKeyChain = astchain.keyChain()
const pKeychain: KeyChain = athchain.keyChain()
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
xKeychain.importKey(privKey)
pKeychain.importKey(privKey)
const xAddresses: Buffer[] = astchain.keyChain().getAddresses()
const pAddressStrings: string[] = athchain.keyChain().getAddressStrings()
const astChainBlockchainID: string =
  Defaults.network[networkID].AST.blockchainID
const athChainBlockchainID: string =
  Defaults.network[networkID].ATH.blockchainID
const exportedOuts: TransferableOutput[] = []
const outputs: TransferableOutput[] = []
const inputs: TransferableInput[] = []
const fee: BN = MILLIDCM
const threshold: number = 1
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
  "Manually Export DCM from ATH-Chain to AST-Chain"
)

const main = async (): Promise<any> => {
  const dcmAssetID: Buffer = await athchain.getDCMAssetID()
  const getBalanceResponse: any = await athchain.getBalance(pAddressStrings[0])
  const unlocked: BN = new BN(getBalanceResponse.unlocked)
  console.log(unlocked.sub(fee).toString())
  const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput(
    unlocked.sub(fee),
    xAddresses,
    locktime,
    threshold
  )
  const transferableOutput: TransferableOutput = new TransferableOutput(
    dcmAssetID,
    secpTransferOutput
  )
  exportedOuts.push(transferableOutput)

  const authorityVMUTXOResponse: any = await athchain.getUTXOs(pAddressStrings)
  const utxoSet: UTXOSet = authorityVMUTXOResponse.utxos
  const utxos: UTXO[] = utxoSet.getAllUTXOs()
  utxos.forEach((utxo: UTXO) => {
    const output: Output = utxo.getOutput()
    // if (output.getOutputID() === 7) {
    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)
    secpTransferInput.addSignatureIdx(0, xAddresses[0])

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

  const exportTx: ExportTx = new ExportTx(
    networkID,
    bintools.cb58Decode(athChainBlockchainID),
    outputs,
    inputs,
    memo,
    bintools.cb58Decode(astChainBlockchainID),
    exportedOuts
  )

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

main()
