/* global Meteor, Mongo */

import Join from './Join';
import Store from './Store';
import { startPublishWorker, stopPublishWorker } from './worker';

const server = {};

function validate(data) {
  const {
    context,
    name,
    interval,
    doJoin,
  } = data;

  // XXX: need to make sure context is an instance of Meteor subscription
  if (typeof context !== 'object') {
    throw new Error('PublishJoin: context must be an instance of subscription, e.g. this inside publication');
  }

  if (typeof name !== 'string') {
    throw new Error('PublishJoin: name of a join must be a string');
  }

  // XXX: should there be any limits of interval?
  if (typeof interval !== 'number') {
    throw new Error('PublishJoin: interval must be a number');
  }

  if (typeof doJoin !== 'function') {
    throw new Error('PublishJoin: doJoin must be a function');
  }
}

if (Meteor.isServer) {
  const store = new Store();

  server.publish = function publish(data) {
    validate(data);

    const join = new Join(data, store, {
      startPublishWorker,
      stopPublishWorker,
    });

    // publish for the 1st
    join.publish();
  };
}

export default server;

@@ -249,16 +249,32 @@
 doJoin,%0A
+    maxWaiting,%0A
   %7D = da
@@ -873,16 +873,175 @@
 n');%0A  %7D
+%0A%0A  if (typeof maxWaiting !== 'number' && typeof maxWaiting !== 'undefined') %7B%0A    throw new Error('PublishJoin: maxWaiting must be a number if provided');%0A  %7D
 %0A%7D%0A%0Aif (
@@ -1257,56 +1257,8 @@
  %7D);
-%0A%0A    // publish for the 1st%0A    join.publish();
 %0A  %7D

Remove calling first time publish manually