'use strict';

const io = require('socket.io-client');

class Pubsub {
  constructor(ipfs) {
    this.ipfs = ipfs;
    this._socket = null;
    this._subscriptions = {};
    this.onConnected = null;
    this.onConnectionError = null;
  }

  connect(host, port, username, password) {
    return new Promise((resolve, reject) => {
      if(!this._socket)
        this._socket = io.connect(`http://${host}:${port}`, { 'forceNew': true });

      this._socket.on('connect', resolve);
      this._socket.on('connect_error', (err) => reject(new Error(`Connection refused to ${host}:${port}`)));
      this._socket.on('disconnect', (socket) => console.log(`Disconnected from http://${host}:${port}`));
      this._socket.on('error', (e) => console.log('Pubsub socket error:', e));
      this._socket.on('message', this._handleMessage.bind(this));
      this._socket.on('subscribed', this._handleMessage.bind(this));
    });
  }

  disconnect() {
    if(this._socket)
      this._socket.disconnect();
  }

  subscribe(hash, password, callback) {
    if(!this._subscriptions[hash]) {
      this._subscriptions[hash] = { callback: callback };
      this._socket.emit('subscribe', { channel: hash }); // calls back with 'subscribed' event
    }
  }

  unsubscribe(hash) {
    this._socket.emit('unsubscribe', { channel: hash });
    delete this._subscriptions[hash];
  }

  publish(hash, message) {
    this._socket.send(JSON.stringify({ channel: hash, message: message }));
  }

  _handleMessage(hash, message) {
    if(this._subscriptions[hash] && this._subscriptions[hash].callback)
      this._subscriptions[hash].callback(hash, message);
  }
}

module.exports = Pubsub;

@@ -17,16 +17,20 @@
 onst io 
+    
 = requir
@@ -51,16 +51,86 @@
 lient');
+%0Aconst logger = require('orbit-common/lib/logger')(%22orbit-db.Pubsub%22);
 %0A%0Aclass 
@@ -635,16 +635,27 @@
 used to 
+Pubsub at '
 $%7Bhost%7D:
@@ -661,16 +661,17 @@
 :$%7Bport%7D
+'
 %60)));%0A  
@@ -716,27 +716,27 @@
 ket) =%3E 
-console.log
+logger.warn
 (%60Discon
@@ -747,16 +747,27 @@
 ed from 
+Pubsub at '
 http://$
@@ -780,16 +780,17 @@
 :$%7Bport%7D
+'
 %60));%0A   
@@ -828,19 +828,20 @@
  =%3E 
-console.log
+logger.error
 ('Pu

Add logger to Pubsub