'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.dispatchRemotely = dispatchRemotely;
exports.dispatchSync = dispatchSync;
exports.subscribe = subscribe;

var _jsan = require('jsan');

var _socketclusterClient = require('socketcluster-client');

var _socketclusterClient2 = _interopRequireDefault(_socketclusterClient);

var _socketOptions = require('../constants/socketOptions');

var _socketOptions2 = _interopRequireDefault(_socketOptions);

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

var socket = void 0;
var channel = void 0;

function dispatchRemotely(type, action, id, bareState) {
  var state = bareState;
  if (type !== 'IMPORT') state = (0, _jsan.stringify)(state);
  socket.emit(id ? 'sc-' + id : 'respond', { type: type, action: action, state: state });
}

function dispatchSync(state, id) {
  socket.emit('respond', { type: 'SYNC', id: id, state: (0, _jsan.stringify)(state) });
}

function subscribe(subscriber) {
  var options = arguments.length <= 1 || arguments[1] === undefined ? _socketOptions2.default : arguments[1];
  var onInstancesChanged = arguments[2];

  if (channel) channel.unwatch();
  if (socket) socket.disconnect();
  try {
    socket = _socketclusterClient2.default.connect(options);
  } catch (error) {
    // FIXME: show in a dialog component
    /* eslint-disable no-alert */
    alert(error.message);
    /* eslint-enable */
    return false;
  }

  function watch(req) {
    var data = void 0;
    if (req.data) {
      data = req.data;
      data.id = req.id;
    } else data = req;

    if (data.type === 'DISCONNECTED') {
      onInstancesChanged(req.id, undefined, true);
      return;
    }
    subscriber(data);
  }

  socket.on('error', function (err) {
    console.error(err);
  });

  socket.on('connect', function () {
    socket.emit('login', {}, function (err, channelName) {
      if (err) {
        console.error(err);return;
      }
      channel = socket.subscribe(channelName);
      channel.watch(watch);
      dispatchRemotely('START');
    });
  });
}