'use strict';

var Command = require('ronin').Command;
var utils = require('../../utils');
var bs58 = require('bs58');
var bl = require('bl');
var fs = require('fs');
var Block = require('ipfs-block');
var debug = require('debug');
var log = debug('cli:block');
log.error = debug('cli:block:error');

function addBlock(buf) {
  utils.getIPFS(function (err, ipfs) {
    if (err) {
      throw err;
    }

    if (utils.isDaemonOn()) {
      return ipfs.block.put(buf, function (err, block) {
        if (err) {
          log.error(err);
          throw err;
        }

        console.log(block.Key);
      });
    }

    var block = new Block(buf);

    ipfs.block.put(block, function (err, obj) {
      if (err) {
        log.error(err);
        throw err;
      }

      console.log(bs58.encode(block.key).toString());
    });
  });
}

module.exports = Command.extend({
  desc: 'Stores input as an IPFS block',

  options: {},

  run: function run(filePath) {
    if (filePath) {
      return addBlock(fs.readFileSync(filePath));
    }

    process.stdin.pipe(bl(function (err, input) {
      if (err) {
        log.error(err);
        throw err;
      }

      addBlock(input);
    }));
  }
});