$(document).ready(function(){
  console.log("in doc ready");
 
   
   //this is for dynamically appended buttons
//   $(document).on('click','.awsparam',function(e){
//         console.log('targer'. e)
//     });
   

                    $('#devlist tbody').on( 'click', 'tr', function (e) {
                        
                        
                        var param = e.target.innerText;

                        
                        if(param !== "" ){
                            var currentRow = $(this).closest('tr').siblings('tr'); 
                            
                        
                            var devname = currentRow.find("td:eq(2)").text(); // get current row 1st TD value
                            var devid = currentRow.find("td:eq(3)").text(); // get current row 2nd TD
                                                  
                            var stTime = moment().subtract({'days': 15}).format('YYYY-MM-DD hh:mm:ss');
    		                var enTime = moment().add({'days': 1}).format('YYYY-MM-DD hh:mm:ss');
 
                            //console.log('cr row ', currentRow.find("td:eq(1)").text());
                            var divid = devid + param
                             console.log("aws param ", divid, param, devid, stTime, enTime);
                            $('#cdyn').append('<div id=' + divid + ' class=\"col-md-3\"></div>');

                           
                            createParamChart(stTime, enTime, devid, param);
                                
                        }

                    });

                   
                    
                    function createParamChart(start, end, id, param) {
                        console.log('div id', id+param);
	
		
		                $.ajax({                                                                                                             	
                               type: "POST",
                               url: 'bcreateParam.php',
                               async:false,
                               data: {start: start, end: end, id: id, param: param },
                               success: function(res)
                               {
                                    console.log('res is ', JSON.parse(res));
                            	    sensData = JSON.parse(res);
                            	    
                            	                                                                                                                                         
                                  var TempMin = [];
                                  var TempAvg = [];
                                  var TextData = [];
                                  
                                  var RainAvg = [];
                                  var RainMinMax = [];
                                  var TextRain = [];
                                  
                                  var RHAvg = [];
                                  var RHMinMax = [];
                                  var TextRH = [];
                                  
                                  var BPAvg = [];
                                  var BPMinMax = [];
                                  var TextBP = [];
                                  
                                  var SolarAvg = [];
                                  var SolarMinMax = [];
                                  var TextSolar = [];
                                  
                                  var WSAvg = [];
                                  var WSMinMax = [];
                                  var TextWS = [];
                                  
                                  var timestamp = [];
                                //   $('.lastupdated').empty();
                                //   $('.lastupdated').html(sensData[sensData.length - 1]["CreationDate"]);
                                                                                                                                                  
                                                                                                                                                  
                                  for (let i = 0; i < sensData.length; i++) {  			
                                  	//Temp Data
                                  	//console.log("Data is ", sensData[i])
                                  	a = {"max": sensData[i]["TMPmax"], "min": sensData[i]["TMPmin"]}
                                  	TempMin[i] = a;
                                  	TempAvg[i] = sensData[i]["TMPavg"]
                                                                                                               
                                  	b = {"max": sensData[i]["RAINmax"], "min": sensData[i]["RAINmin"]}
                                  	RainAvg[i] = sensData[i]["RAINavg"]
                                  	RainMinMax[i] = b
                                                                                                               
                                  	c = {"max": sensData[i]["BPmax"], "min": sensData[i]["BPmin"]}
                                  	BPAvg[i] = sensData[i]["BPavg"]
                                  	BPMinMax[i] = c
                                                                                                               
                                  	d = {"max": sensData[i]["RHmax"], "min": sensData[i]["RHmin"]}
                                  	RHAvg[i] = sensData[i]["RHavg"]
                                  	RHMinMax[i] = d
                                                                                                               
                                  	e = {"max": sensData[i]["SOLARmax"], "min": sensData[i]["SOLARmin"]}
                                  	SolarAvg[i] = sensData[i]["SOLARavg"]
                                  	SolarMinMax[i] = e
                                                                                                               
                                  	f = {"max": sensData[i]["WSmax"], "min": sensData[i]["WSmin"]}
                                  	WSAvg[i] = sensData[i]["WSavg"]
                                  	WSMinMax[i] = f
                                                                                                               
                                  	timestamp[i] =  sensData[i]["CreationDate"]
                                  }
                                           
                                // console.log("Temp data", TempAvg, RHAvg, BPAvg, SolarAvg, WSAvg, RainAvg, TempMin)                                                                                                                  
                                                                                                                                                  
                                  for (let i = 0; i < TempAvg.length; i++) { 
                                  	TextData[i] = "Max: " + TempMin[i]["max"].toString() + " Min: " + TempMin[i]["min"].toString()
                                  }
                                  for (let i = 0; i < RainAvg.length; i++) { 
                                  	TextRain[i] = "Max: " + RainMinMax[i]["max"].toString() + " Min: " + RainMinMax[i]["min"].toString()
                                  }
                                  for (let i = 0; i < RHAvg.length; i++) { 
                                  	TextRH[i] = "Max: " + RHMinMax[i]["max"].toString() + " Min: " + RHMinMax[i]["min"].toString()
                                  }
            	                  for (let i = 0; i < SolarAvg.length; i++) { 
                                  	TextSolar[i] = "Max: " + SolarMinMax[i]["max"].toString() + " Min: " + SolarMinMax[i]["min"].toString()
                                  }
                                  for (let i = 0; i < BPAvg.length; i++) { 
                                  	TextBP[i] = "Max: " + BPMinMax[i]["max"].toString() + " Min: " + BPMinMax[i]["min"].toString()
                                  }
                                  for (let i = 0; i < WSAvg.length; i++) { 
                                  	TextWS[i] = "Max: " + WSMinMax[i]["max"].toString() + " Min: " + WSMinMax[i]["min"].toString()
                                  }
                                  
                                  
                                  
                                  var RainAvg2 = {
                                    y: RainAvg,
                                    x : timestamp,
                                    type: 'lines',
                                    name: 'Rain Avg',
                                    text : TextRain
                                };
                                
                                var TempAvg2 = {
                                    y: TempAvg,
                                    x : timestamp,
                                    text : TextData,
                                    name: 'Temperature Avg',
                                    type: 'lines'
                                  };
                                  
                                  
                                  var SolarAvg2 = {
                                    y: SolarAvg,
                                    x : timestamp,
                                    type: 'lines',
                                    name: 'Solar Avg',
                                    text : TextSolar
                                  };
                                  var WSAvg2 = {
                                    y: WSAvg,
                                    x : timestamp,
                                    type: 'lines',
                                    name: 'Ws Avg',
                                    text : TextWS
                                  };
                                  var BPAvg2 = {
                                    y: BPAvg,
                                    x : timestamp,
                                    type: 'lines',
                                    name: 'BP Avg',
                                    text : TextWS
                                  };
                      
                                
                                var layout = {
                                    hovermode:'closest',
                                    title: 'AWS Data',
                                    width: 300,
                                    height: 300,
                                };
                                var data = [RainAvg2];
                                var data1 = [TempAvg2];
                                var data2 = [BPAvg2];
                                var data3 = [SolarAvg2];
                                var data4 = [WSAvg2];
                                var data5 = [RainAvg2];
                                
                                //var data = [TempAvg2, RainAvg2, BPAvg2, SolarAvg2, WSAvg2];
                                //console.log('mplot', mPlot);
                                var config = {responsive: true}
                                console.log('rain avg', RainAvg2, RainAvg);
                                console.log('div id', id+param);
                                
                      
                                Plotly.newPlot(id+param, data, layout, config);
                                // Plotly.newPlot('temp2', data1, layout, config);
                                // Plotly.newPlot('temp3', data2, layout, config);
                                // Plotly.newPlot('temp4', data3, layout, config);
                                // Plotly.newPlot('temp5', data4, layout, config);
                                // Plotly.newPlot('temp6', data5, layout, config);
                                
                                  
                                                                                                                                                              
                                  //parseData(resParse)
                               }
		                });
                    }                                  
                    
                    
  $("#addev").submit(function(e){
	e.preventDefault();
	var form = $(this);
    console.log('add dev', form.serialize());
    	$.ajax({
           type: "POST",
           url: 'badd-dev.php',
           data: form.serialize(), // serializes the form's elements.
           success: function(res)
           {
		resPars = JSON.parse(res);
		toastr.options = {                   	
                  "closeButton": true,
                  "debug": false,
                  "newestOnTop": false,
                  "progressBar": false,
                  "positionClass": "toast-top-right",
                  "preventDuplicates": false,
                  "onclick": null,
                  "showDuration": "300",
                  "hideDuration": "1000",
                  "timeOut": "5000",
                  "extendedTimeOut": "1000",
                  "showEasing": "swing",
                  "hideEasing": "linear",
                  "showMethod": "fadeIn",
                  "hideMethod": "fadeOut"
                }
                if (resPars.warning) {toastr["warning"]( resPars.warning );}
                if (resPars.success) {toastr["success"]( resPars.success );}
                if (resPars.error) {toastr["error"]( resPars.error );}

           },
           error: function() {
                console.log("unsuccessful");

	   }
        });
  })

  $("#devup").submit(function(e){
      console.log("in update")
        e.preventDefault();
        var form = $(this);
	    console.log('serial', form.serialize());
	    let queryString = window.location.search;
                                          
    	$.ajax({
          type: "POST",
          url: 'bdev-edit.php?devid='+  queryString.substring(1).split("=")[1],
          data: form.serialize(), // serializes the form's elements.
          success: function(res)
          {
		    console.log("json", res);
        	resPars = JSON.parse(res);
        	toastr.options = {                   	
                  "closeButton": true,
                  "debug": false,
                  "newestOnTop": false,
                  "progressBar": false,
                  "positionClass": "toast-top-right",
                  "preventDuplicates": false,
                  "onclick": null,
                  "showDuration": "300",
                  "hideDuration": "1000",
                  "timeOut": "5000",
                  "extendedTimeOut": "1000",
                  "showEasing": "swing",
                  "hideEasing": "linear",
                  "showMethod": "fadeIn",
                  "hideMethod": "fadeOut"
                }
                if (resPars.warning) {toastr["warning"]( resPars.warning );}
                if (resPars.success) {toastr["success"]( resPars.success );}
                if (resPars.error) {toastr["error"]( resPars.error );}
                                                                             
          },
          error: function() {
                console.log("unsuccessful");
                                                                             
          }
        });
  })


  var id = "";                                          
  $(".delpopup").click(function(e) {
      delDevice(id);
  
  });

  $(".delc").click(function(e){
     console.log("del clicked");
     id = $(this).closest('tr').find("#id").context.id;
     $("#delmodal").modal();
   });

   function delDevice(id) {
       $.ajax({
           async: false,
           type: 'POST',
           url: 'deldevice.php',
           data: {token: id},
           success: function(result) {
	       console.log("del device", result);
               getall();
               
           },
           error: function(err) {
		console.log("error ", err);
           }
       });
   }


    function getall() {               
	setTimeout(() => {  console.log("Reloading"); }, 2000);
	window.location.reload()
    }

})