var http = require('http');
var W3CWebSocket = require('websocket').w3cwebsocket;

var http_port = 12345;
//Create a server object
http.createServer(function (req, res) {
    handlerReq(req.url, res);
}).listen(http_port);

var reportMsg ="0";
var reportMsg1 ="0";
var reportMsg2 ="0";
var reportMsg3 ="0";
var reportMsg4 ="0";
var reportMsg5 ="0";

var ws = "ud";
var poll_index = 0;
var data;
var i=0;
var serialPort = require('serialport')
var Readline = require('@serialport/parser-readline')
var port = new serialPort("COM8", { baudRate: 57600 })     //baudRate: 230400 
var parser = new Readline()
var dec=0,dec1=0;
    
 var sensor1,sensor2,sensor3,sensor4;
 var sensor1=66;
 var inbyte;

 port.on('open',function(){
  console.log('Open port');
});                


function handlerReq(url, res)
{

  res.data=1;
        var cmdStr = decodeURI(url);
    var cmdArr = cmdStr.split("/");
    
    if (ws!=null){
                                 
        if (ws.readyState === ws.OPEN)
        {         
            switch(cmdArr[1])
            {
            case "poll":
              poll_index ++;
					// Only process one time for each 10 poll requests
                    if(poll_index >=2)
                    {
                      poll_index = 0;
                     
                     const ByteLenght=serialPort.parsers.ByteLength;
                     const parser=port.pipe(new ByteLenght({length: 7}));
                     
                       parser.on('data',function(data)
                        {                                                 
                          if(data[0]==81)
                          {
                            reportMsg = ('DRead/'+1+" "+data[1]+"\n");                                                                                 
                            reportMsg1 = ('DRead/'+2+" "+data[2]+"\n");                             
                            reportMsg2 = ('DRead/'+3+" "+data[3]+"\n");                                                                                
                            reportMsg3 = ('DRead/'+4+" "+data[4]+"\n"); 
			    reportMsg4 = ('DRead/'+5+" "+data[5]+"\n");                                                                                
                            reportMsg5 = ('DRead/'+6+" "+data[6]+"\n"); 
                          }
                        });
                            console.log('data:',data);     
                            res.write(reportMsg);res.write(reportMsg1);res.write(reportMsg2);
                            res.write(reportMsg3);res.write(reportMsg4);res.write(reportMsg5); 
                    }                                
                   break;
                case "reset_all":
                    break;
        case "Yss":                                                   
                     console.log(cmdArr[1]); //bayraa
                     console.log(cmdArr[2]); //bayraa
                     port.write(cmdArr[1] +cmdArr[2]  )                     
                    break;
       case "NOT":                                                    

                      console.log(cmdArr[1]); //bayraa
                      console.log(cmdArr[2]); //bayraa
                      console.log(cmdArr[3]); //bayraa
                      port.write(cmdArr[1] +cmdArr[2]+cmdArr[3]  )                     
                     break;
        case "dC": //DC Motor        
                      console.log(cmdArr[1]); 
                      console.log(cmdArr[2]); 
                      console.log(cmdArr[3]); 
                      console.log(cmdArr[4]); 
                      console.log('E');                 
                      port.write( cmdArr[1] +cmdArr[2] +cmdArr[3] +cmdArr[4][0] +'&')   
                //      port.write( cmdArr[1] +cmdArr[2] +cmdArr[3] +cmdArr[4])                                        
                      break;    
      
	case "Lig":        
                        console.log(cmdArr[1]); //bayraa
                        console.log(cmdArr[2]); //bayraa
                        console.log(cmdArr[3]); //bayraa
                        console.log(cmdArr[4]); //bayraa   
			port.write( cmdArr[1][0] + cmdArr[1][1] + cmdArr[1][2] + cmdArr[2][0] + cmdArr[3][0] + cmdArr[4][0] + ' ' + '%')
                     //   port.write( cmdArr[1] +cmdArr[2] +cmdArr[3] +cmdArr[4]+'E' )                      
                        break;// bayraa  

         case "srW":                   
                     break;// bayraa

                         }
            res.end();
       }
		else {
			res.write('_problem Connecting to PHPoC device\r\n');
			res.end();
		}
    }
    else{
        if (cmdArr[1] == "ipW"){
        }
		res.write('_problem Not connected to PHPoC device\r\n');
		res.end();
        
    }
   
}

function ws_onerror() {
    console.log('WebSocket Connection Error');
	//ws = null;
         ws = "ipW";
};

function ws_onopen() {
    console.log('WebSocket Client Connected');
};

function ws_onclose() {
    console.log('WebSocket Client Closed');
	//ws = null;
          ws = "ipW";
};

function ws_onmessage(msg) {
    if (typeof msg.data === 'string') {
       // reportMsg = msg.data;
        ws = "ipW";
    }

};
/*function readSerialData(data) {
    console.log(data);
    // if there are webSocket connections, send the serial data
    // to all of them:
    if (connections.length > 0) {
      broadcast(data);
    }
 }*/



