(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(['module'], factory);
  } else if (typeof exports !== "undefined") {
    factory(module);
  } else {
    var mod = {
      exports: {}
    };
    factory(mod);
    global.myvtexSSE = mod.exports;
  }
})(this, function (module) {
  'use strict';

  module.exports = function myvtexSSE(account, workspace, path) {
    var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
      verbose: false
    };
    var callback = arguments[4];

    var env = /myvtexdev\.com/.test(window.location.hostname) ? 'myvtexdev' : 'myvtex';
    var host = options.host || workspace + '--' + account + '.' + env + '.com';
    var url = 'https://' + host + '/_v/sse/' + path;
    var eventSource = new EventSource(url);

    if (options.verbose) {
      eventSource.addEventListener('open', function () {
        return console.log('[myvtex-sse] Connected to path \'' + path + '\'.');
      });
      eventSource.addEventListener('error', function (err) {
        return console.log('[myvtex-sse] Error from path \'' + path + '\':', err);
      });
      eventSource.addEventListener('message', function (message) {
        return console.log('[myvtex-sse] Message from path \'' + path + '\':', message);
      });
    }

    if (callback && typeof callback === 'function') {
      var listener = function listener(_ref) {
        var data = _ref.data;

        try {
          data = JSON.parse(data);
        } catch (e) {
          console.error('[myvtex-sse] Failed to parse message\'s data to JSON');
        }
        callback(data);
      };

      eventSource.addEventListener('message', listener);
    }

    // Client might want to add multiple listeners, handle open and close, etc.
    return eventSource;
  };
});