import { Dcomm, BinTools, BN, Buffer } from "dcomm/dist"
import { EVMAPI, KeyChain as EVMKeyChain } from "dcomm/dist/apis/evm"
import {
  AuthorityVMAPI,
  KeyChain,
  SECPTransferOutput,
  SECPTransferInput,
  TransferableOutput,
  TransferableInput,
  UTXOSet,
  UTXO,
  AmountOutput,
  UnsignedTx,
  Tx,
  ExportTx
} from "dcomm/dist/apis/authorityvm"
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 actchain: EVMAPI = dcomm.ACTChain()
const athchain: AuthorityVMAPI = dcomm.ATHChain()
const bintools: BinTools = BinTools.getInstance()
const cKeychain: EVMKeyChain = actchain.keyChain()
const pKeychain: KeyChain = athchain.keyChain()
let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
// AST-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p
cKeychain.importKey(privKey)
pKeychain.importKey(privKey)

privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4"
// ATH-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj
cKeychain.importKey(privKey)
pKeychain.importKey(privKey)
const cAddresses: Buffer[] = actchain.keyChain().getAddresses()
const pAddresses: Buffer[] = athchain.keyChain().getAddresses()
const pAddressStrings: string[] = athchain.keyChain().getAddressStrings()
const actChainBlockchainID: string =
  Defaults.network[networkID].ACT.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 = 2
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
  "Manually Export DCM from ATH-Chain to ACT-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),
    cAddresses,
    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): void => {
    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, pAddresses[0])
    if (utxo.getOutput().getThreshold() === 2) {
      secpTransferInput.addSignatureIdx(1, pAddresses[1])
    }

    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(actChainBlockchainID),
    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()
