import { Dcomm, BinTools, BN, Buffer } from "dcomm/dist"
import {
  AuthorityVMAPI,
  KeyChain,
  SECPTransferOutput,
  SECPTransferInput,
  TransferableOutput,
  TransferableInput,
  UTXOSet,
  UTXO,
  AmountOutput,
  UnsignedTx,
  Tx,
  AddSubnetValidatorTx
} from "dcomm/dist/apis/authorityvm"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  NodeIDStringToBuffer,
  Defaults
} from "dcomm/dist/utils"

const bintools: BinTools = BinTools.getInstance()
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 athchain: AuthorityVMAPI = dcomm.ATHChain()
// Keychain with 4 keys-A, B, ACT, and D
const pKeychain: KeyChain = athchain.keyChain()
// Keypair A
let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
// ATH-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p
pKeychain.importKey(privKey)

// Keypair B
privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4"
// ATH-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj
pKeychain.importKey(privKey)

// Keypair ACT
privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW"
// ATH-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45
pKeychain.importKey(privKey)

// Keypair D
privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn"
// ATH-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq
pKeychain.importKey(privKey)
const pAddresses: Buffer[] = athchain.keyChain().getAddresses()
const pAddressStrings: string[] = athchain.keyChain().getAddressStrings()
const athChainBlockchainID: string =
  Defaults.network[networkID].ATH.blockchainID
const athChainBlockchainIDBuf: Buffer =
  bintools.cb58Decode(athChainBlockchainID)
const outputs: TransferableOutput[] = []
const inputs: TransferableInput[] = []
const fee: BN = athchain.getDefaultTxFee()
const threshold: number = 1
const locktime: BN = new BN(0)
const nodeID: string = "NodeID-NFBbbJ4qCmNaCzeW7sxErhvWqvEQMnYcN"
const startTime: BN = new BN(1652146558)
const endTime: BN = new BN(1653442362)
const memo: Buffer = Buffer.from(
  "Manually create a AddSubnetValidatorTx which creates a 1-of-2 DCM utxo and adds a validator to a subnet by correctly signing the 2-of-3 SubnetAuth"
)
const dcmUTXOKeychain: Buffer[] = [pAddresses[0], pAddresses[1]]

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)
  const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput(
    unlocked.sub(fee),
    dcmUTXOKeychain,
    locktime,
    threshold
  )
  const transferableOutput: TransferableOutput = new TransferableOutput(
    dcmAssetID,
    secpTransferOutput
  )
  outputs.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])

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

  const weight: BN = new BN(1)
  const subnetID: Buffer = bintools.cb58Decode(
    "yKRV4EvGYWj7HHXUxSYzaAQVazEvaFPKPhJie4paqbrML5dub"
  )
  const nodeIDBuf: Buffer = NodeIDStringToBuffer(nodeID)
  const addSubnetValidatorTx: AddSubnetValidatorTx = new AddSubnetValidatorTx(
    networkID,
    athChainBlockchainIDBuf,
    outputs,
    inputs,
    memo,
    nodeIDBuf,
    startTime,
    endTime,
    weight,
    subnetID
  )
  addSubnetValidatorTx.addSignatureIdx(0, pAddresses[3])
  addSubnetValidatorTx.addSignatureIdx(1, pAddresses[1])
  const unsignedTx: UnsignedTx = new UnsignedTx(addSubnetValidatorTx)
  const tx: Tx = unsignedTx.sign(pKeychain)
  const txid: string = await athchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
