'use strict';

var Command = require('ronin').Command;
var utils = require('../../../utils');
var bs58 = require('bs58');
var debug = require('debug');
var log = debug('cli:object');
var mDAG = require('ipfs-merkle-dag');
var DAGLink = mDAG.DAGLink;
log.error = debug('cli:object:error');

module.exports = Command.extend({
  desc: 'Add a link to a given object',

  options: {},

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

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

      if (utils.isDaemonOn()) {
        return ipfs.object.patch.addLink(root, name, ref, function (err, obj) {
          if (err) {
            log.error(err);
            throw err;
          }

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

      // when running locally we first need to get the ref object,
      // so we can create the link with the correct size
      var refMh = new Buffer(bs58.decode(ref));
      ipfs.object.get(refMh, function (err, linkedObj) {
        if (err) {
          log.error(err);
          throw err;
        }

        var rootMh = new Buffer(bs58.decode(root));
        var link = new DAGLink(name, linkedObj.size(), linkedObj.multihash());
        ipfs.object.patch.addLink(rootMh, link, function (err, obj) {
          if (err) {
            log.error(err);
            throw err;
          }

          console.log(bs58.encode(obj.multihash()).toString());
        });
      });
    });
  }
});