'use strict';

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

module.exports = Command.extend({
  desc: 'Get a raw IPFS block',

  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.block.get(mh, function (err, block) {
        if (err) {
          log.error(err);
          throw err;
        }

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

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