'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var multiaddr = require('multiaddr');
var loadCommands = require('./load-commands');
var getConfig = require('./default-config');
var getRequestAPI = require('./request-api');

function IpfsAPI(hostOrMultiaddr, port, opts) {
  var config = getConfig();

  try {
    var maddr = multiaddr(hostOrMultiaddr).nodeAddress();
    config.host = maddr.address;
    config.port = maddr.port;
  } catch (e) {
    if (typeof hostOrMultiaddr === 'string') {
      config.host = hostOrMultiaddr;
      config.port = port && (typeof port === 'undefined' ? 'undefined' : _typeof(port)) !== 'object' ? port : config.port;
    }
  }

  var lastIndex = arguments.length;
  while (!opts && lastIndex-- > 0) {
    opts = arguments[lastIndex];
    if (opts) break;
  }

  Object.assign(config, opts);

  // autoconfigure in browser
  if (!config.host && typeof window !== 'undefined') {
    var split = window.location.host.split(':');
    config.host = split[0];
    config.port = split[1];
  }

  var requestAPI = getRequestAPI(config);
  var cmds = loadCommands(requestAPI);
  cmds.send = requestAPI;
  cmds.Buffer = Buffer;

  return cmds;
}

exports = module.exports = IpfsAPI;