'use strict';

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

module.exports = Command.extend({
  desc: 'Outputs the raw bytes in an IPFS object',

  options: {},

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

    utils.getIPFS(function (err, ipfs) {
      if (err) {
        throw err;
      }
      var mh = utils.isDaemonOn() ? key : new Buffer(bs58.decode(key));

      ipfs.object.data(mh, function (err, data) {
        if (err) {
          log.error(err);
          throw err;
        }

        if (data instanceof Buffer) {
          console.log(data.toString());
          return;
        }

        // js-ipfs-api output (http stream)
        data.pipe(process.stdout);
      });
    });
  }
});