'use strict';

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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: 'Get and serialize the DAG node named by <key>',

  options: {},

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

    utils.getIPFS(function (err, ipfs) {
      if (err) {
        throw err;
      }
      if (utils.isDaemonOn()) {
        return ipfs.object.get(key, function (err, obj) {
          if (err) {
            log.error(err);
            throw err;
          }

          console.log((0, _stringify2.default)(obj));
        });
      }

      var mh = new Buffer(bs58.decode(key));
      ipfs.object.get(mh, function (err, obj) {
        if (err) {
          log.error(err);
          throw err;
        }

        console.log((0, _stringify2.default)({
          Links: obj.links.map(function (link) {
            return {
              Name: link.name,
              Hash: bs58.encode(link.hash).toString(),
              Size: link.size
            };
          }),
          Data: obj.data.toString()
        }));
      });
    });
  }
});