import { Component, Inject, OnInit } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../../../contact.service';
declare var $: any;

@Component({
  selector: 'app-summary-details',
  templateUrl: './summary-details.component.html',
  styleUrls: ['./summary-details.component.scss']
})
export class SummaryDetailsComponent implements OnInit {
 Load : Boolean = false;
 tabelObj;
 summary
    constructor(public dialogRef: MdDialogRef<SummaryDetailsComponent>,private contactService: ContactService,
    @Inject(MD_DIALOG_DATA) public data: any) {
      console.log(data);
      
     }

  ngOnInit() {
    this.testTable()
  }



  testTable() {
  const that = this;
  console.log("inside function");
 
  $(document).ready(function() {
 
     that.tabelObj = $('#detailsTable').DataTable({
        dom: 'lBftip',
        buttons: [
          'copy',
          'print',
          'excel'
        ],       
          "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          // "scrollY":'63vh',     
          // "scrollX": true,
          // "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
         
          ajax: (dataTablesParameters,callback) => {
            that.summary=that.data.trips
            if (that.summary.length != 0) {
                var j = 0;
                var finalArr = [];
                for (var i = 0; i < that.summary.length; i++) {
  
                  that.clocation_1(that.summary[i], function (err, succ) {
                    if (err) {
                      console.log(err);
                      j++;
                    } else {
                      finalArr.push(succ);
                      console.log(finalArr);
                      j++;
                      if (j === that.summary.length) {
                        that.Load = false;
                        var x = [];
                        finalArr.sort(function(a,b){
                          // Turn your strings into dates, and then subtract them
                          // to get a value that is either negative, positive, or zero.
                          var aDate:any = new Date(a.Date);
                          var bDate:any = new Date(b.Date);  
                          return bDate - aDate;
                        });
                
                        
                        callback({ data: finalArr });
                      }
                    }
                  })
  
                 
                }
              } else {
                that.Load = false;
                callback({ data: [] });
  
              }
           
            // callback({ data: that.data.trips });
 
        },  
      
          "columns": [
            {
              "data": "device",
              "defaultContent": "",
              "render": function (data, type, row) {  
                        
                return (data.length != 0) ? data.Device_Name : '';
              }
            },
     
            {
              "data": "startAddress",
              "defaultContent": "",
              render: function (data, type, row) {
                console.log(data);
                
                  if(data){
                     return  data?data:''; 
                  }else{
                    let lat = row.start_lat?row.start_lat:null;
                    let long = row.start_long?row.start_long:null;       
                    var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle Start location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';            

                    return  addressLink;  
                  }
              
              }
            },    
            {
              "data": "endAddress",
              "defaultContent": "",
              render: function (data, type, row) {
               if(data){
                     return  data?data:''; 
                  }else{
                    let lat = row.end_lat?row.end_lat:null;
                    let long = row.end_long?row.end_long:null;       
                    var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle Start location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';            

                    return  addressLink;  
                  } 
              
              }
            }, 
            {
              "data": "distance",
              "defaultContent": "",
              render: function (data, type, row) {

                return data?(data/1000).toFixed(2) : "00.00";
              }
            },    
       
            {
              "data": "start_time",
              "defaultContent": "",
              render: function (data, type, row) {

                return that.convertDate(data);
              }
            },
            {
              "data": "end_time",
              "defaultContent": "",
              render: function (data, type, row) {

                 return that.convertDate(data);
              }
            },                                  
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3,4,5] },
          //   {
          //     "targets": '_all',
          //     "createdCell": function (td, cellData, rowData, row, col) {
          //         $(td).css('padding', '18px')
          //     }
          // }   
           
         
          ] 
      });

  });

}




tab:any;
  exportExcel()
	{
   console.log("Export");
   

	    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
	    var textRange; var j=0;
      var table = $('#detailsTable').clone();
    
      table[0].querySelector("thead").remove();
      table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];
    console.log(this.tab);
    
  
	    for(j = 0 ; j < this.tab.rows.length ; j++) 
	    {     
	        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
	     
	    }

	    tab_text=tab_text+"</table>";
	 
	    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); 

	    var ua = window.navigator.userAgent;
	    var msie = ua.indexOf("MSIE "); 

	    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

	    return (sa);
  }
  convertDate(inputFormat) {
          function pad(s) { return (s < 10) ? '0' + s : s; }
            var d = new Date(inputFormat)
           return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')
              }

clocation_1(latlngObj, cb) {
    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };
    if (latlngObj.start_lat) {
      latLng = {
        lat: latlngObj.start_lat ? latlngObj.start_lat : 0,
        long: latlngObj.start_long ? latlngObj.start_long : 0
      }
    }
    if (latlngObj.today_start_location) {
      latLng = {
        lat: latlngObj.today_start_location.lat ? latlngObj.today_start_location.lat : 0,
        long: latlngObj.today_start_location.long ? latlngObj.today_start_location.long : 0
      }
    }

    // if () {
    //   latLng = {
    //     lat: 0,
    //     long: 0
    //   }
    // }

    outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
      if (res.message == "Address not found in databse") {
        latlngObj['startAddress'] = "NA";
        // cb(null,latlngObj);
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_location) {
          latLng_1 = {
            lat: latlngObj.end_location.lat ? latlngObj.end_location.lat : 0,
            long: latlngObj.end_location.long ? latlngObj.end_location.long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

      } else {
        latlngObj['startAddress'] = res.address;
        var latLng_1 = {
          lat: "0",
          long: "0"
        };
        if (latlngObj.last_location) {
          latLng_1 = {
            lat: latlngObj.last_location.lat ? latlngObj.last_location.lat : 0,
            long: latlngObj.last_location.long ? latlngObj.last_location.long : 0
          }

        }
        if (latlngObj.end_lat) {
          latLng_1 = {
            lat: latlngObj.end_lat ? latlngObj.end_lat : 0,
            long: latlngObj.end_long ? latlngObj.end_long : 0
          }
        }


        outerThis.contactService.getAddressByApi(latLng_1).subscribe(res => {
          if (res.message == "Address not found in databse") {
            latlngObj['endAddress'] = "NA";
            cb(null, latlngObj);


          } else {
            latlngObj['endAddress'] = res.address;
            cb(null, latlngObj);
          }

        })

        // cb(null,latlngObj);
      }
    })

  }

}
// created_on: "2021-04-07T20:34:44.702Z"
// device: {_id: "606c396343ddd6513f49112a", Device_Name: "MH14HG0107", Device_ID: "866551038377268"}
// distance: 2642.9293113737913
// endAddress: "Chinchwad, Pune, 411019, Pimpri-Chinchwad, India, Maharashtra"
// end_lat: "18.650116666666666"
// end_long: "73.80517333333333"
// end_time: "2021-04-07T20:34:44.684Z"
// startAddress: "136, Mahatma Phule Marg, Mohan Nagar, MIDC, Chinchwad, Pimpri-Chinchwad, Maharashtra 411019, India"
// start_lat: "18.646631666666668"
// start_long: "73.79820611111111"
// start_time: "2021-04-07T20:22:58.212Z"
// user: "5cee7da97a38f414a4e5dfa3"