export default class Subscription {
  constructor(store, api, channel) {
    this.store = store;
    this.api = api;
    this.channel = channel;

    this.channel.setOnChannelError(this.onChannelError.bind(this));
    this.firstRoundComplete = false;
  }

  start() {
    if (this.api.ship) {
      this.firstRound();
    } else {
      console.error('~~~ ERROR: Must set api.ship before operation ~~~');
    }
  }

  delete() {
    this.channel.delete();
  }

  onChannelError(err) {
    console.error('event source error: ', err);
    console.log('initiating new channel');
    this.firstRoundComplete = false;
    setTimeout(2000, () => {
      this.store.handleEvent({
        data: { clear : true }
      });

      this.start();
    });
  }

  subscribe(path, app) {
    this.api.bind(path, 'PUT', this.api.ship, app,
      this.handleEvent.bind(this),
      (err) => {
        console.log(err);
        this.subscribe(path, app);
      },
      () => {
        this.subscribe(path, app);
      });
  }

  firstRound() {
    this.subscribe('/sole/' + this.api.dojoId, 'dojo');
  }

  handleEvent(diff) {
    this.store.handleEvent(diff);
  }
}


@@ -404,16 +404,770 @@
 ;%0A    %7D%0A
+    this.setupSlog();%0A  %7D%0A%0A  setupSlog() %7B%0A    const slog = new EventSource('/~/slog', %7B withCredentials: true %7D);%0A    let available = false;%0A%0A    slog.onopen = e =%3E %7B%0A      console.log('slog: opened stream');%0A      available = true;%0A    %7D%0A%0A    slog.onmessage = e =%3E %7B%0A      this.handleEvent(%7B txt: e.data %7D);%0A    %7D%0A%0A    slog.onerror = e =%3E %7B%0A      console.error('slog: eventsource error:', e);%0A      if (!available) %7B%0A        this.handleEvent(%7B txt:%0A          'landscape: no printf stream. bad connection or old binary.'%0A        %7D);%0A      %7D else %7B%0A        window.setTimeout(() =%3E %7B%0A          if (slog.readyState !== EventSource.CLOSED) return;%0A          console.log('slog: reconnecting...');%0A          this.setupSlog();%0A        %7D, 10000);%0A      %7D%0A    %7D%0A
   %7D%0A%0A  d

connect to slog stream for printfs