var tls = require('tls');
var config = require(process.env.HOME + '/.nodifier/config.js');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var fs = require('fs');
var options = {
    key: fs.readFileSync(process.env.HOME + '/.nodifier/nodifier-key.pem'),
    cert: fs.readFileSync(process.env.HOME + '/.nodifier/nodifier-cert.pem'),
    ca: fs.readFileSync(process.env.HOME + '/.nodifier/nodifier-cert.pem'),
    rejectUnauthorized: true
};

var socketConnect = function() {
    var recvBuffer = "";

    var self = this;
    var socket;

    var reconnectTimeout;
    var connect = function(callback) {
        socket = tls.connect(config.port, config.host, options, function() {
            socket.on('data', function(data) {
				// message format is assumed to be:
				// 1234["string", {...}]
				// where 1234 is message length
				recvBuffer += data.toString();

				// recv'd the msg length integer if we have a '[' char
				var msgLenEnd = recvBuffer.indexOf('[');
				if(msgLenEnd !== -1) {
					var len = recvBuffer.substr(0, msgLenEnd);
					var msg = recvBuffer.substr(msgLenEnd, len);

					// got entire msg?
					if(msg.length == len) {
						// remove msg from buffer, then handle it
						recvBuffer = recvBuffer.substr(msgLenEnd + len);

						data = JSON.parse(msg);
						if(data[0] !== 'data')
							self.emit(data[0], data[1]);
					}
				}
            });

            self.emit('open');
        });

        var reconnect = function(e) {
            if(!e)
                e = '';
            console.log('DEBUG: Reconnecting... ' + e);
            clearTimeout(reconnectTimeout);
            reconnectTimeout = setTimeout(connect, 1000);
        };

        socket.once('close', function() {
            reconnect();
        });
        socket.once('error', function(e) {
            reconnect(e);
        });

        socket.setKeepAlive(true);
    };

    connect();

    this.send = function(evt, data) {
        data = JSON.stringify([evt, data]);
        socket.write(data.length.toString());
        socket.write(data);
    };
    this.close = function() {
        socket.removeAllListeners('close');
        socket.end();
    };
}

util.inherits(socketConnect, EventEmitter);

module.exports = socketConnect;

@@ -753,20 +753,32 @@
 data) %7B%0A
-%09%09%09%09
+                
 // messa
@@ -805,20 +805,32 @@
  to be:%0A
-%09%09%09%09
+                
 // 1234%5B
@@ -846,20 +846,32 @@
  %7B...%7D%5D%0A
-%09%09%09%09
+                
 // where
@@ -894,20 +894,32 @@
  length%0A
-%09%09%09%09
+                
 recvBuff
@@ -942,20 +942,66 @@
 ing();%0A%0A
-%09%09%09%09
+                while(true) %7B%0A                    
 // recv'
@@ -1047,20 +1047,36 @@
 %5B' char%0A
-%09%09%09%09
+                    
 var msgL
@@ -1108,20 +1108,36 @@
 f('%5B');%0A
-%09%09%09%09
+                    
 if(msgLe
@@ -1151,21 +1151,40 @@
 = -1) %7B%0A
-%09%09%09%09%09
+                        
 var len 
@@ -1185,16 +1185,25 @@
 r len = 
+parseInt(
 recvBuff
@@ -1225,23 +1225,43 @@
 gLenEnd)
+)
 ;%0A
-%09%09%09%09%09
+                        
 var msg 
@@ -1302,67 +1302,127 @@
 );%0A%0A
-%09%09%09%09%09// got entire msg?%0A%09%09%09%09%09if(msg.length == len) %7B%0A%09%09%09%09%09%09
+                        // got entire msg?%0A                        if(msg.length == len) %7B%0A                            
 // r
@@ -1459,22 +1459,44 @@
 ndle it%0A
-%09%09%09%09%09%09
+                            
 recvBuff
@@ -1541,114 +1541,348 @@
 );%0A%0A
-%09%09%09%09%09%09data = JSON.parse(msg);%0A%09%09%09%09%09%09if(data%5B0%5D !== 'data')%0A%09%09%09%09%09%09%09self.emit(data%5B0%5D, data%5B1%5D);%0A%09%09%09%09%09%7D%0A%09%09%09%09
+                            data = JSON.parse(msg);%0A                            if(data%5B0%5D !== 'data')%0A                                self.emit(data%5B0%5D, data%5B1%5D);%0A                        %7D%0A                    %7D else %7B%0A                        break;%0A                    %7D%0A                %7D else %7B%0A                    break;%0A                
 %7D%0A  

fix annoying bug causing everything not to be received sometimes