import { stringify } from 'jsan';
import socketCluster from 'socketcluster-client';
import socketOptions from '../constants/socketOptions';

let socket;
let channel;

export function subscribe(subscriber, options = socketOptions, onInstancesChanged) {
  if (channel) channel.unwatch();
  if (socket) socket.disconnect();
  socket = socketCluster.connect(options);

  function watch(req) {
    let data;
    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', {}, (err, channelName) => {
      if (err) { console.error(err); return; }
      channel = socket.subscribe(channelName);
      channel.watch(watch);
      dispatchRemotely('UPDATE');
    });
  });
}

export function dispatchRemotely(type, action, id, state) {
  socket.emit(
    id ? 'sc-' + id : 'respond',
    { type, action, state: state ? stringify(state) : undefined }
  );
}

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

@@ -160,16 +160,328 @@
 annel;%0A%0A
+export function dispatchRemotely(type, action, id, state) %7B%0A  socket.emit(%0A    id ? 'sc-' + id : 'respond',%0A    %7B type, action, state: state ? stringify(state) : undefined %7D%0A  );%0A%7D%0A%0Aexport function dispatchSync(state, id) %7B%0A  socket.emit(%0A    'respond',%0A    %7B type: 'SYNC', id, state: stringify(state) %7D%0A  );%0A%7D%0A%0A
 export f
@@ -1272,316 +1272,4 @@
 ;%0A%7D%0A
-%0Aexport function dispatchRemotely(type, action, id, state) %7B%0A  socket.emit(%0A    id ? 'sc-' + id : 'respond',%0A    %7B type, action, state: state ? stringify(state) : undefined %7D%0A  );%0A%7D%0A%0Aexport function dispatchSync(state, id) %7B%0A  socket.emit(%0A    'respond',%0A    %7B type: 'SYNC', id, state: stringify(state) %7D%0A  );%0A%7D%0A

Fix linting