const fs = require('fs');
const ndjson = require('ndjson');
const RestClient = require('../../../api/RestClient');
const { subcommand, println } = require('../../util');


const BATCH_SIZE = 1000;

module.exports = {
  command: 'put [filename]',
  description: 'Read newline-delimited JSON data from `filename` or stdin and store in the remote node as IPLD.\n',
  builder: {
    batchSize: { default: BATCH_SIZE }
  },

  handler: subcommand(opts => {
    const { client, batchSize, filename } = opts;
    const streamName = filename || 'standard input';

    let items = [];
    let promises = [];

    let inputStream;
    if (filename) {
      inputStream = fs.createReadStream(filename);
    } else {
      inputStream = process.stdin;
    }

    return new Promise((resolve, reject) => {
      inputStream.pipe(ndjson.parse()).on('data', obj => {
        items.push(obj);
        if (items.length >= batchSize) {
          promises.push(putItems(client, items));
          items = [];
        }
      }).on('end', () => {
        if (items.length > 0) {
          promises.push(putItems(client, items));
        }
        Promise.all(promises).then(() => resolve());
      }).on('error', err => {
        err = new Error(`Error reading from ${ streamName }: ${ err.message }`);
        reject(err);
      });
    });
  })
};

function putItems(client, items) {
  return client.putData(...items).then(hashes => {
    hashes.forEach(h => println(h));
  });
}