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

privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4"
// AST-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj
xKeychain.importKey(privKey)
pKeychain.importKey(privKey)

privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9"
// ATH-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte
xKeychain.importKey(privKey)
pKeychain.importKey(privKey)
const xAddresses: Buffer[] = astchain.keyChain().getAddresses()
const xAddressStrings: string[] = astchain.keyChain().getAddressStrings()
const pAddresses: Buffer[] = athchain.keyChain().getAddresses()
const astChainID: string = Defaults.network[networkID].AST.blockchainID
const astChainIDBuf: Buffer = bintools.cb58Decode(astChainID)
const dcmAssetID: string = Defaults.network[networkID].AST.dcmAssetID
const dcmAssetIDBuf: Buffer = bintools.cb58Decode(dcmAssetID)
const athChainID: string = Defaults.network[networkID].ATH.blockchainID
const athChainIDBuf: Buffer = bintools.cb58Decode(athChainID)
const exportedOuts: TransferableOutput[] = []
const outputs: TransferableOutput[] = []
const inputs: TransferableInput[] = []
const fee: BN = astchain.getDefaultTxFee()
const threshold: number = 2
const locktime: BN = new BN(0)
const memo: Buffer = Buffer.from(
  "Export DCM from the AST-Chain to the ATH-Chain and create a multisig atomic utxo"
)

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),
    pAddresses,
    locktime,
    threshold
  )
  const transferableOutput: TransferableOutput = new TransferableOutput(
    dcmAssetIDBuf,
    secpTransferOutput
  )
  exportedOuts.push(transferableOutput)

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

    const secpTransferInput: SECPTransferInput = new SECPTransferInput(amount)
    secpTransferInput.addSignatureIdx(0, xAddresses[0])

    const input: TransferableInput = new TransferableInput(
      txID,
      outputIdx,
      dcmAssetIDBuf,
      secpTransferInput
    )
    inputs.push(input)
  })

  const exportTx: ExportTx = new ExportTx(
    networkID,
    astChainIDBuf,
    outputs,
    inputs,
    memo,
    athChainIDBuf,
    exportedOuts
  )
  const unsignedTx: UnsignedTx = new UnsignedTx(exportTx)
  const tx: Tx = unsignedTx.sign(xKeychain)
  const txid: string = await astchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
