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

var http_port = 20185;
//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 = null;
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("/");
    
  //  port.off();
    
    if (ws!=null){

   //=========bayraa serial =========//               
    
    // Read data that is available but keep the stream from entering //"flowing mode"
  //  port.on('readable', function () {
    //    console.log('Data:', port.read());
  //  });
    //=========================

     //   parser.on('data', line =>sensor1= `> ${line[1]}`) 
      // console.log(sensor1);           
       // port.write( cmdArr[2] )
    //qqq=sensor1+30;
                     



       // console.log(cmdArr[2]); //bayraa                
        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;
                     // data[0]=0;//data[1]=0,data[2]=0,data[3]=0;
                     //i=0;
                     //inbyte=port.read();// bayraa
                     const ByteLenght=serialPort.parsers.ByteLength;
                     const parser=port.pipe(new ByteLenght({length: 5}));
                     //for( var p=0; p<1; p++)
                     //{
                       parser.on('data',function(data)
                        {                       
                          //while( data[i]!=81 && i>11 ){ i++; }
                          if(data[0]==81)
                          {
                           // var ccc=data[8]+data[7]+data[6];
                            //if(ccc=246)
                            if(data[1]==0 )
                            {
                              reportMsg = ('DRead/'+0+" "+0+"\n"); 
                            }
                            else{ reportMsg = ('DRead/'+0+" "+1+"\n"); }                          

                            if(data[2]==0)
                            {                                                       
                              reportMsg1 = ('DRead/'+1+" "+0+"\n"); 
                            }
                            else{ reportMsg1 = ('DRead/'+1+" "+1+"\n"); }
                            if(data[3]==0 )
                            {
                              reportMsg2 = ('DRead/'+2+" "+0+"\n"); 
                            }
                            else{ reportMsg2 = ('DRead/'+2+" "+1+"\n"); }                          

                            if(data[4]==0)
                            {                                                       
                              reportMsg3 = ('DRead/'+3+" "+0+"\n"); 
                            }
                            else{ reportMsg3 = ('DRead/'+3+" "+1+"\n"); }

                            /*if(data[5]==48 )
                            {
                              reportMsg4 = ('DRead/'+4+" "+0+"\n"); 
                            }
                            else{ reportMsg4 = ('DRead/'+4+" "+1+"\n"); } */                       
                           /* console.log('data:',data);     
                            res.write(reportMsg);res.write(reportMsg1);res.write(reportMsg2);
                            res.write(reportMsg3); */                  
                            //p=33;
                          }
                        });
                            console.log('data:',data);     
                            res.write(reportMsg);res.write(reportMsg1);res.write(reportMsg2);
                            res.write(reportMsg3); 
                       // res.write(reportMsg);res.write(reportMsg1);res.write(reportMsg2);
                       // res.write(reportMsg3);//res.write(reportMsg4);
                      //}
                    //  parser.off('data',function(data);

                        //res.write(reportMsg3);
                        //console.log(inbyte);
                        
                       // console.log(reportMsg3);
                        //console.log(i);
                        
                     // res.end();
                     // }

                    }
              
                  
                   break;
                case "reset_all":
             //       ws.send(cmdStr + "/\r\n");
		//			ws.close();
                    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])   
                      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] +cmdArr[2] +cmdArr[3] +cmdArr[4]+'E' )                      
                        break;// bayraa  

         case "srW":
                   // ws.send(cmdStr + "/\r\n");
                   // break;
                   
                     break;// bayraa

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

        //    console.log('ws://'+cmdArr[2]+'/scratch_test');
         //   ws = new W3CWebSocket('ws://'+cmdArr[2]+'/scratch_test', 'csv.phpoc');
          //  ws.onerror = ws_onerror;
          //  ws.onopen = ws_onopen;
         //   ws.onclose = ws_onclose;
         //   ws.onmessage = ws_onmessage;

        }
		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);
    }
 }*/



