/**
 * Copyright (c) 2018-present, Leap DAO (leapdao.org)
 *
 * This source code is licensed under the Mozilla Public License Version 2.0
 * found in the LICENSE file in the root directory of this source tree.
 */

/* eslint-disable no-await-in-loop, no-console, no-loop-func */

const Web3 = require('web3');
const axios = require('axios');
const { helpers, Tx, Outpoint } = require('leap-core');

const web3 = new Web3('https://rinkeby.infura.io');
const plasmaJsonRpc = 'https://testnet-node1.leapdao.org';
const privKey =
  '0xbd54b17c48ac1fc91d5ef2ef02e9911337f8758e93c801b619e5d178094486cc';

const account = web3.eth.accounts.privateKeyToAccount(privKey);

const poorManRpc = url => (method, params) => {
  return axios({
    method: 'post',
    url,
    data: JSON.stringify({ jsonrpc: "2.0", id: 2895, method, params }),
    headers: { 'Content-Type': 'application/json' },
  }).then(resp => resp.data.result);
}

async function run() {
  const rpc = poorManRpc(plasmaJsonRpc);

  for (let i = 0; i < (process.env.NUM || 1); i += 1) {
    // calc inputs
    const utxos = (await rpc("plasma_unspent", [account.address]))
      .map(u => ({
        output: u.output,
        outpoint: Outpoint.fromRaw(u.outpoint),
      }));

    if (utxos.length === 0) {
      throw new Error(`Not enough balance for machine gun. Send some LEAPs to ${account.address}`);
    }

    const inputs = helpers.calcInputs(utxos, account.address, 100, 0);

    const outputs = helpers.calcOutputs(
      utxos, inputs, account.address, account.address, 100, 0
    );

    const tx = Tx.transfer(inputs, outputs).signAll(privKey);

    console.log(tx.toJSON()); // eslint-disable-line no-console

    // eslint-disable-next-line no-console
    console.log(await rpc("eth_sendRawTransaction", [tx.hex()])); 
  }
}

run();
