'use strict';

var websocket = require('websocket-stream'),
  _URL = require('url'),
  wssProperties = [
    'rejectUnauthorized',
    'ca',
    'cert',
    'key',
    'pfx',
    'passphrase'
  ];

function buildBuilder (client, opts) {
  var wsOpt = {
      protocol: 'mqtt'
    },
    host = opts.hostname || 'localhost',
    port = String(opts.port || 80),
    path = opts.path || '/',
    url = opts.protocol + '://' + host + ':' + port + path;
  if (('MQIsdp' === opts.protocolId) && (3 === opts.protocolVersion)) {
    wsOpt.protocol = 'mqttv3.1';
  }

  if ('wss' === opts.protocol) {
    wssProperties.forEach(function (prop) {
      if (opts.hasOwnProperty(prop)) {
        wsOpt[prop] = opts[prop];
      }
    });
  }

  return websocket(url, wsOpt);
}

function buildBuilderBrowser (mqttClient, opts) {
  var url, parsed;
  if ('undefined' !== typeof (document)) { // for Web Workers! P.S: typeof(document) !== undefined may be becoming the faster one these days.
    parsed = _URL.parse(document.URL);
  } else {
    throw new Error('Could not determine host. Specify host manually.');
  }

  if (!opts.protocol) {
    if ('https:' === parsed.protocol) {
      opts.protocol = 'wss';
    } else {
      opts.protocol = 'ws';
    }
  }

  if (!opts.hostname) {
    opts.hostname = opts.host;
  }

  if (!opts.hostname) {
    opts.hostname = parsed.hostname;
    if (!opts.port) {
      opts.port = parsed.port;
    }
  }

  if (!opts.port) {
    if ('wss' === opts.protocol) {
      opts.port = 443;
    } else {
      opts.port = 80;
    }
  }

  if (!opts.path) {
    opts.path = '/';
  }

  url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path;

  return websocket(url, 'mqttv3.1');
}

if ('browser' !== process.title) {
  module.exports = buildBuilder;
} else {
  module.exports = buildBuilderBrowser;
}
