'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.startMonitoring = startMonitoring;
exports.createRemoteStore = createRemoteStore;
exports.updateStoreInstance = updateStoreInstance;
exports.enableSync = enableSync;
exports.importState = importState;
exports.exportState = exportState;

var _createDevStore = require('./createDevStore.js');

var _createDevStore2 = _interopRequireDefault(_createDevStore);

var _updateState = require('./updateState');

var _updateState2 = _interopRequireDefault(_updateState);

var _messaging = require('../services/messaging');

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

var store = void 0;
var instance = void 0;
var shouldSync = false;

function sync(state, id) {
  if (shouldSync) (0, _messaging.dispatchSync)(state, id);
}

function startMonitoring(id) {
  (0, _messaging.dispatchRemotely)('START', undefined, id);
}

function createRemoteStore(socketOptions, onInstancesChanged, onError, newInstance) {
  store = (0, _createDevStore2.default)(_messaging.dispatchRemotely);
  instance = newInstance;
  (0, _messaging.subscribe)(function (msg) {
    if (msg.type === 'STOP') {
      // Stopped by other monitor
      startMonitoring(msg.id);
      return;
    }
    if (msg.type === 'ERROR') {
      onError(msg.payload);
      return;
    }
    (0, _updateState2.default)(store, msg, onInstancesChanged, instance, sync);
  }, socketOptions, onInstancesChanged);
  return store;
}

function updateStoreInstance(newInstance) {
  instance = newInstance;
  if (newInstance) store.liftedStore.setInstance(instance);
  shouldSync = false;
}

function enableSync(should) {
  shouldSync = should;
}

function importState(state) {
  store.liftedStore.importState(state);
}

function exportState() {
  return store.liftedStore.getState();
}