#!/usr/bin/env node
/*jshint esversion:6, node:true*/
'use strict';

var Socket = require('net').Socket;
var encrypt = require('../lib/utils').encrypt;
var Commands = require('../lib/utils').COMMANDS;
var parseCommand = require('../lib/utils').parseCommand;
////////////////////////
///
////////////////////////

module.exports = function(config){
    console.log('Connecting to %s %s', config.host, config.port);

    var socket = new Socket();

    socket.connect(parseInt(config.port), config.host);

    socket.on('data', function handshakeHanlder(data){
        console.log('on data', data.toString());
        var payload = parseCommand(data);
        switch(payload.cmd){
            case Commands.AUTHORIZE:
                var seed = payload.getSeed();
                var payload = encrypt(program.user + ' ' + program.pass, seed);
                socket.write(payload);
            break;
            case Commands.EXIT:
                var verbose = true;
                var label = payload.getErrorMessage(verbose);
                fdone(label);
            break;
            case Commands.CONNECT:
                socket.removeListener('data', handshakeHanlder);
                handleConnection(socket);
            break;
            default:
                console.log('Command not recognized');
                console.log('CMD: %s', payload.cmd);
                console.log('Original payload: %s', data.toString());
            break;
        }
    });
    socket.on('close', fdone.bind(null, 'socket:close'));
    socket.on('error', fdone.bind(null, 'socket:error'));

    var signals = ['exit', 'error', 'unhandledException', 'SIGINT'];
    signals.map((signal) =>{
        process.on(signal, fdone.bind(null, signal));
    });

    function handleConnection(socket){
        if(handleConnection.piping) return;
        handleConnection.piping = true;

        process.stdin.setRawMode(true);

        process.stdin.pipe(socket);
        socket.pipe(process.stdout);

        process.stdin.on('end', () => socket.destroy());

        process.stdin.on('data', (b) =>{
            if(b.length === 1 && b[0] === 4){
                process.stdin.setRawMode(false);
                process.stdin.emit('end');
            }
        });
    }

    function fdone(label, e){
        if(fdone.called) return;
        fdone.called = true;

        console.log('HANDLE EXIT CALL: %s label', label);

        if(e){
            console.log(e);
            if(e.message) console.error(e.message);
            if(e.stack) console.error(e.stack);
        }

        try {
            process.stdin.setRawMode(false);
        } catch(e){console.log('ERROR', e.message);}

        socket.removeListener('close', fdone);
        socket.destroy();
        process.exit();
    }
};

@@ -438,16 +438,152 @@
 ocket();
+%0A    socket.on('close', closeConnection.bind(null, 'socket:close'));%0A    socket.on('error', closeConnection.bind(null, 'socket:error'));
 %0A%0A    so
@@ -654,25 +654,16 @@
 ('data',
- function
  handsha
@@ -675,64 +675,48 @@
 lder
-(data)%7B%0A        console.log('on data', data.toString());
+);%0A%0A    function handshakeHanlder(data)%7B
 %0A   
@@ -904,23 +904,22 @@
 encrypt(
-program
+config
 .user + 
@@ -928,15 +928,14 @@
 ' + 
-program
+config
 .pas
@@ -1148,21 +1148,31 @@
         
-fdone
+closeConnection
 (label);
@@ -1373,16 +1373,63 @@
 efault:%0A
+                console.log('--------------');%0A
         
@@ -1511,16 +1511,17 @@
 'CMD: %25s
+.
 ', paylo
@@ -1603,37 +1603,65 @@
 ));%0A            
-break
+    console.log('--------------')
 ;%0A        %7D%0A    
@@ -1658,132 +1658,34 @@
     
-%7D%0A
     
-%7D)
+break
 ;%0A    
-socket.on('close', fdone.bind(null, 'socket:close'));%0A    socket.on('error', fdone.bind(null, 'socket:error'))
+    %7D%0A    %7D
 ;%0A%0A 
@@ -1808,21 +1808,31 @@
 signal, 
-fdone
+closeConnection
 .bind(nu
@@ -2376,21 +2376,31 @@
 unction 
-fdone
+closeConnection
 (label, 
@@ -2415,16 +2415,76 @@
     
-if(fdone
+console.log('closeConnection', label, e);%0A        if(closeConnection
 .cal
@@ -2504,21 +2504,31 @@
         
-fdone
+closeConnection
 .called 
@@ -2905,13 +2905,23 @@
 e', 
-fdone
+closeConnection
 );%0A 

clean up and reorganize;