'use strict';

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

function parseAndAddNode(keyStr, data) {
  utils.getIPFS(function (err, ipfs) {
    if (err) {
      throw err;
    }

    var key = utils.isDaemonOn() ? keyStr : new Buffer(bs58.decode(keyStr));

    ipfs.object.patch.setData(key, data, function (err, obj) {
      if (err) {
        log.error(err);
        throw err;
      }

      if (typeof obj.multihash === 'function') {
        console.log(bs58.encode(obj.multihash()).toString());
        return;
      }

      console.log(obj.Hash);
    });
  });
}

module.exports = Command.extend({
  desc: 'Set data field of an ipfs object',

  options: {},

  run: function run(key, filePath) {
    if (!key) {
      throw new Error("Argument 'root' is required");
    }

    if (filePath) {
      return parseAndAddNode(key, fs.readFileSync(filePath));
    }

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

      parseAndAddNode(key, input);
    }));
  }
});