'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 links pointed to by the specified 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.links(mh, function (err, links) {
        if (err) {
          log.error(err);
          throw err;
        }

        if (links.Links) {
          // js-ipfs-api output
          links.Links.forEach(function (link) {
            console.log(link.Hash, link.Size, link.Name);
          });
          return;
        }

        links.forEach(function (link) {
          console.log(bs58.encode(link.hash).toString(), link.size, link.name);
        });
      });
    });
  }
});