var redis = require('redis');
var listener = redis.createClient();
var sender = redis.createClient();

var evts = require('events');
var messenger = new evts.EventEmitter();
var myName;
var sendQueue = [];

messenger.send = function(to, eventName, content){
   if(!myName){
      sendQueue.push({
         to: to,
         data: {
            content:content,
            eventName: eventName
         }
      });
      var emsg = "Cannot send without registering yourself. This will send automatically when registered!";
      console.error(emsg);
      return new Error(emsg);
   }
   sender.publish(to, JSON.stringify({
      content: content,
      eventName: eventName,
      from: myName,
   }));
};

listener.on('message', function(channel, message){
   var msg;
   try {
      msg = JSON.parse(message);
   } catch(e){
      console.error(e);
      return console.error("Message Contents:", message);
   }
   messenger.emit(msg.eventName, msg.content, msg.from, channel);
});

// checks if a channel is still open
messenger.isAlive = function(id, callback){
   getChannels(function(channels){
      if(channels.indexOf(id) === -1){
         callback(false);
         return;
      }
      callback(true);
   });
};

// idea: create/return a new client for join?
messenger.join = function(channel){
   listener.subscribe(channel);
};

messenger.leave = function(channel){
   listener.unsubscribe(channel);
};

messenger.register = function(me){
   console.log('registering as: ', me);
   if(!me){
      me = makeId();
      console.log("No name given, generating random name: ", me);
   }
   getChannels(function(channels){
      if(channels.indexOf(me) !== -1){
         var newMe = !!me ? ""+me+makeId() : makeId();
         console.log("Warning: a channel with name \""+me+"\" already Exists... Created new channel: ", newMe);
         if(channels.indexOf(newMe) !== -1){
            throw new Error("Could not randomize unique channel name");
         }
         me = newMe;
      }
      myName = me;
      listener.subscribe(me);
      flushSendQueue();
   });
};

messenger.whoAmI = function(){
   return myName;
};

module.exports = {
   create: function(){
      return messenger;
   }
};

process.on('SIGINT', function(){
   console.log("got SIGINT from: ", myName);
   if(myName){
      console.log("unsubscribing from:", myName);
      listener.unsubscribe(myName);
   }
   process.exit();
});

process.on('SIGTERM', function(){
   console.log("got SIGTERM");
   if(myName){
      console.log("unsubscribing from:", myName);
      listener.unsubscribe(myName);
   }
   process.exit();
});

process.on('SIGHUP', function(){
   console.log("got SIGHUP");
   if(myName){
      console.log("unsubscribing from:", myName);
      listener.unsubscribe(myName);
   }
   process.exit();
});



// misc functions

function flushSendQueue(){
   sendQueue.forEach(function(msg){
      msg.data.from = myName;
      sender.publish(msg.to, JSON.stringify(msg.data));
   });
   sendQueue = [];
}

function getChannels(callback){
   sender.pubsub('channels', function(a, channels){
      callback(channels || []);
   });
}

function makeId(){
   return Math.random().toString(36).substring(2);
}

@@ -2075,732 +2075,289 @@
 %7D;%0A%0A
-messenger.whoAmI = function()%7B%0A   return myName;%0A%7D;%0A%0Amodule.exports = %7B%0A   create: function()%7B%0A      return messenger;%0A   %7D%0A%7D;%0A%0Aprocess.on('SIGINT', function()%7B%0A   console.log(%22got SIGINT from: %22, myName);%0A   if(myName)%7B%0A      console.log(%22unsubscribing from:%22, myName);%0A      listener.unsubscribe(myName);%0A   %7D%0A   process.exit();%0A%7D);%0A%0Aprocess.on('SIGTERM', function()%7B%0A   console.log(%22got SIGTERM%22);%0A   if(myName)%7B%0A      console.log(%22unsubscribing from:%22,
+// using this function will prevent messenger from receiving events on its channel%0Amessenger.unregister = function()%7B%0A   listener.unsubscribe(myName);%0A%7D;%0A%0Amessenger.whoAmI = function()%7B%0A   return
  myName
-)
 ;%0A
-      listener.unsubscribe(myName);%0A   %7D%0A   process.exit();%0A%7D);%0A%0Aprocess.on('SIGHUP', function()%7B%0A   console.log(%22got SIGHUP%22);%0A   if(myName)%7B%0A      console.log(%22unsubscribing from:%22, myName);%0A      list
+%7D;%0A%0Amodule.exports = %7B%0A   create: function()%7B%0A      return mess
 en
+g
 er
-.unsubscribe(myName);%0A   %7D%0A   process.exit();%0A%7D);%0A%0A
+;%0A   %7D%0A%7D;
 %0A%0A//

remove signal handlers as those should be application specific