'use strict';

var _typeof2 = require('babel-runtime/helpers/typeof');

var _typeof3 = _interopRequireDefault(_typeof2);

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

var fs = require('fs');
var os = require('os');
var APIctl = require('ipfs-api');
var multiaddr = require('multiaddr');
var IPFS = require('../core');
var path = require('path');
var debug = require('debug');
var log = debug('cli');
log.error = debug('cli:error');

exports = module.exports;

exports.isDaemonOn = isDaemonOn;
function isDaemonOn() {
  try {
    fs.readFileSync(path.join(exports.getRepoPath(), 'api'));
    log('daemon is on');
    return true;
  } catch (err) {
    log('daemon is off');
    return false;
  }
}

exports.getAPICtl = getAPICtl;
function getAPICtl() {
  if (!isDaemonOn()) {
    throw new Error('daemon is not on');
  }
  var apiPath = path.join(exports.getRepoPath(), 'api');
  var apiAddr = multiaddr(fs.readFileSync(apiPath).toString());
  return APIctl(apiAddr.toString());
}

exports.getIPFS = function (callback) {
  if (!isDaemonOn()) {
    var _ret = function () {
      var ipfs = new IPFS(exports.getRepoPath());
      ipfs.load(function () {
        callback(null, ipfs);
      });
      return {
        v: void 0
      };
    }();

    if ((typeof _ret === 'undefined' ? 'undefined' : (0, _typeof3.default)(_ret)) === "object") return _ret.v;
  }

  callback(null, getAPICtl());
};

exports.getRepoPath = function () {
  return process.env.IPFS_PATH || os.homedir() + '/.ipfs';
};