"use strict";

var _tape = _interopRequireDefault(require("tape"));

var _eventsource = _interopRequireDefault(require("eventsource"));

var _reduxBundler = require("redux-bundler");

var _getEventSourceManager = require("./get-event-source-manager");

var _waitFor = require("../utils/wait-for");

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

const getStore = actionObserver => (0, _reduxBundler.composeBundlesRaw)(_reduxBundler.appTimeBundle, (0, _reduxBundler.createReactorBundle)({
  idleTimeout: 100,
  cancelIdleWhenDone: false
}), (0, _getEventSourceManager.getEventSourceManagerBundle)({
  name: 'eventSource',
  eventSourceConstructor: _eventsource.default,
  actionBaseName: 'EVENT_SOURCE',
  dataActionCreatorName: 'doReceiveQuery',
  activeIdsSelectorName: 'selectEventSourceIds',
  buildUrl: () => 'https://dev.api.xchart.com/taskbar-gateway/sse/cfd/cfd_taskbar_JIkQnWaPD28c_ZUUQBCdV?taskbarId=o0lC9',
  selectEventSourceIds: () => ['hi'],
  selectEventSourceStatus: (0, _reduxBundler.createSelector)('selectEventSourceRaw', raw => {
    const first = Object.values(raw)[0];

    if (!first) {
      return 'none';
    }

    return first.state;
  }),
  selectIsNone: (0, _reduxBundler.createSelector)('selectEventSourceStatus', status => status === 'none'),
  selectIsConnecting: (0, _reduxBundler.createSelector)('selectEventSourceStatus', status => status === 'connecting'),
  selectIsFailed: (0, _reduxBundler.createSelector)('selectEventSourceStatus', status => status === 'failed'),
  retryFailedTimeout: 350,
  logger: {
    error: () => {},
    debug: () => {}
  }
}), {
  name: 'observer',
  getMiddleware: () => () => next => action => {
    const result = next(action);
    actionObserver(action);
    return result;
  }
})();

(0, _tape.default)('getEventSourceManagerBundle handles errors', t => {
  let count = 0;
  let startTime = Date.now();
  const store = getStore(action => {
    // ignore these
    if (action.type === 'APP_IDLE') {
      return;
    }

    let timeSince = Date.now() - startTime;
    count++;

    if (count === 1) {
      t.equal(action.type, 'EVENT_SOURCE_CREATED');
    }

    if (count === 2) {
      t.equal(action.type, 'EVENT_SOURCE_FAILED');
    }

    if (count === 3) {
      t.ok(timeSince > 300, 'should have been a while');
      t.equal(action.type, 'EVENT_SOURCE_REMOVED');
    }

    if (count === 4) {
      store.destroy();
      t.equal(action.type, 'EVENT_SOURCE_CREATED');
      t.end();
    }
  });
  t.equal(store.selectEventSourceStatus(), 'none', 'should be none at first');
  (0, _waitFor.waitFor)(store, 'selectIsFailed').then(() => {
    t.equal(store.selectEventSourceStatus(), 'failed', 'should now be failed');
  });
});