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

@Component({
  selector: 'app-daily-details',
  templateUrl: './daily-details.component.html',
  styleUrls: ['./daily-details.component.scss']
})
export class DailyDetailsComponent implements OnInit {
  Load: boolean;
  Fromdate: any;
  todate: any;
  useridd: any;
  skip: any;
  deviceArr: any;
  reportArr: any[];
  firstcall: boolean;
  lastcall: boolean;
date:any;
device_id:any
mainData
Running
Idle
Stop
DeviceName
  constructor(public dialogRef: MdDialogRef<DailyDetailsComponent>,private contactService: ContactService,
    @Inject(MD_DIALOG_DATA) public data: any) {
       console.log('data=>',data);
       this.mainData=data.data
       this.Running=this.millisecondConversion(this.mainData.today_running);
       this.Idle=this.millisecondConversion(this.mainData.t_idling);
       this.Stop=this.millisecondConversion(this.mainData.today_stopped);
       this.date=data.date;
        this.DeviceName=this.mainData.Device_Name
       this.device_id=data.data._id
     
    }


  ngOnInit() {
    this.testTable()
  }
  // Start Time	Start Location	Start Odometer	Start Coordinate	Reach Time	Reach Location	End Odometer	Reach Coordinate	Driver	Distance	Total Distance	Running 	Idle	Stop	AVG	MAX	Over Speed	Alert

  tabelObj: any ;
testTable() {
  const that = this;
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#dailyDetailsTable').DataTable({
             
          "processing": false,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          responsive: true,
          "scrollY":'60vh',  
          "scrollCollapse": true,  
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            "rowCallback": function(row: Node, data: any | Object, index: number){

             
            },
          ajax: (dataTablesParameters,callback) => {
           
              var deviceID;
              
              that.Load = true;
            var from_date = that.Fromdate;
            var to_date = that.todate;
            var user = that.useridd;
            var temp = {
            from_date : from_date,
            to_date : to_date,
            user : user
            }
        // user_trip/StoppageLogs?date=2020-12-31T11:48:45.670Z&device=5fc8af44aa0b1b5f1b778fcf
            var suburl = "";
            var limit = 26;
            suburl += "/user_trip/StoppageLogs?date=" + that.date +"&device="+that.device_id
            // if(that.deviceArr.length != 0){  
            //   suburl +='&device='+that.deviceArr;
            // }
            that.contactService.get(suburl).subscribe((resp:any) => {   
                that.Load = false;  
                that.reportArr = [];
                that.reportArr= resp.result ;           
                if (that.reportArr.length != 0) {
                  var j = 0;
                  console.log(that.reportArr);
                  
                  var finalArr =  []
                  // console.log(finalArr);
                  for (var i = 0; i < that.reportArr.length; i++) {
                  
    
                    that.clocation_1(that.reportArr[i], function (err, succ) {
                      if (err) {
                        console.log(err);
                        j++;
                      } else {
                        finalArr.push(succ);
                        console.log(finalArr);
                        j++;
                        if (j === that.reportArr.length) {
                          that.Load = false;
                          finalArr.sort((a, b) => new Date(b.start_time).valueOf() - new Date(a.start_time).valueOf());
                          callback({ data: finalArr });
                        }
                      }
                    })
    
                   
                  }
                } else {
                  that.Load = false;
                  that.firstcall=true;
                  that.lastcall=(that.skip>0)?false:true;
                  callback({ data: [] });
    
                }
            }, err => {   
              that.Load= false;    
              callback({ data: [] });
              console.log("error",err) ;     
            });
        },  "aaSorting": [],
          "columns": [
              {
                  "data": "type",
                  "render": function(data, type, row) {                   
                    return row.type;
                  }
              },
               {
                  "data": "start_time",
                  "render": function(data, type, row) {  
                    var start_time
                     if(row != undefined){
                  //  start_time =  row.start_time;
                   start_time =moment(row.start_time).format('lll')
                  }else{
                    start_time = '0:0'
                  }
                    return start_time;
                  }
              },
              {
                  "data": "startAddress",
                  "render": function(data, type, row) {  
                    
                    return data;
                  }
              },
              {
                  "data": "end_time",
                  "render": function(data, type, row) {  
                     var end_time
                     if(row != undefined){
                  //  end_time =  row.end_time;
                    end_time =moment(row.end_time).format('lll')  
                  }else{
                    end_time = '0:0'
                  }
                    return end_time;
                  }                 
                    // return end_time;
                  },
                  
              {
                  "data": "endAddress",
                  "render": function(data, type, row) {  
                     
                    return data;
                  }                 
                    // return end_time;
                  },
              
               {
                  "data": "event_time",
                  "render": function(data, type, row) { 
                      var event_time
                     if(row != undefined){
                       
                   event_time =  that.millisecondConversion(parseInt(row.event_time));
                  }else{
                    event_time = '0:0'
                  }
                    return event_time;
                  }   
                    // return row.event_time;
                  },
                  {
                  "data": "distance",
                  "render": function(data, type, row) { 
                      var distance
                  if(row.distance != undefined){
                      distance =  (row.distance/1000).toFixed(2);
                  }else{
                    distance = '0:0'
                  }
                    return distance;
                  }   
                    
                  }
              // },
     
          ],  
          "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')
          //     }
          // } ,
          { "width": "10px", "targets": 0 },
          { "width": "40px", "targets": 1 },
          { "width": "100px", "targets": 2 },
          { "width": "70px", "targets": 3 },  
          { "width": "10px", "targets": 4 },
          { "width": "10px", "targets": 5 },   
 
    //       {
    //     targets: -1, //-1 es la ultima columna y 0 la primera
    //     data: null,
    //     defaultContent: '<div class="btn-group"> <button (click)="show()">view</button></div>'
    // },
          ] 
      });
      // that.tabelObj.sort

  });

}

millisecondConversion(duration){
  
  // var  minutes = Math.floor((duration / (1000 * 60)) % 60);
  //   var  hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
    
  //   hours = (hours < 10) ? 0 + hours : hours;
  //   minutes = (minutes < 10) ? 0 + minutes : minutes;
    
  //   return hours + ":" + minutes ;
    
    var x = duration;
    var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
return  hours + ":" + mins;
  
}
millisecondConversion2(totalSeconds){
  var minute= totalSeconds/60000
  var second=0
  var totalTime
  if(minute>=60){
    totalTime=minute/60
  }else{
    totalTime=minute
  }
  console.log(totalTime);
  
  return totalTime;
  // var hours   = Math.floor(totalSeconds / 3600);
  // var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  // var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // // round seconds
  // seconds = Math.round(seconds * 100) / 100

  // var result = (hours < 10 ? "0" + hours : hours);
  //     result += "-" + (minutes < 10 ? "0" + minutes : minutes);
  //     result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
  // return result;

}
exportExcel() {
  for(var i=0;i<this.reportArr.length;i++){
    if(this.reportArr[i].event_time)
    this.reportArr[i].event_time=this.millisecondConversion(parseInt(this.reportArr[i].event_time));
    if(this.reportArr[i].distance)
    this.reportArr[i].distance=(this.reportArr[i].distance/1000).toFixed(2);
  }
    this.downloadFile(this.reportArr);
  }

  downloadFile(data, filename = 'Trip Details') {
   
    let arrHeader = ["type", "start_time", "startAddress", "end_time","endAddress","event_time","distance"];
    let csvData = this.ConvertToCSV(data, arrHeader);
    let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
    let dwldLink = document.createElement("a");
    let url = URL.createObjectURL(blob);
    let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1;
    if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
      dwldLink.setAttribute("target", "_blank");
    }
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", "Trip Details.csv");
    dwldLink.style.visibility = "hidden";
    document.body.appendChild(dwldLink);
    dwldLink.click();
    document.body.removeChild(dwldLink);
  }
  ConvertToCSV(objArray, headerList) {
    let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    // console.log(array,"<===");Distance	126.94
// Running	2:1
// Idle	1:56
// Stop
    
    let str = 'Trip Details \r\n'+this.DeviceName+"   "+this.date+" \r\n"+"Distance: "+(this.mainData.today_odo).toFixed(2)+" \r\n"+
    "Running:"+this.Running+" \r\n"+"Idle:"+this.Idle+" \r\n"+"Stop:"+this.Stop+" \r\n \r\n";
    let row = 'S.No,';

    let newHeaders =["Event", "Start Time", "Start Location", "End Time","End Location","Duration","Total K.M."];

    for (let index in newHeaders) {
      row += newHeaders[index] + ',';
    }
    row = row.slice(0, -1);
    str += row + '\r\n';
    for (let i = 0; i < array.length; i++) {
      let line = (i + 1) + '';
      if(i<array.length){}
      for (let index in headerList) {
        let head = headerList[index];       
        line += ',' + this.strRep(array[i][head]);
      }
      str += line + '\r\n';
      
    }
    return str;
  }

  strRep(data) {
    if(typeof data == "string") {
      let newData = data.replace(/,/g, " ");
       return newData;
    }
    else if(typeof data == "undefined") {
      return "-";
    }
    else if(typeof data == "number") {
      return  data.toString();
    }
    else {
      return data;
    }
  }
tab:any;
  exportExcels()
	{
   console.log("Export");
   

	    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
	    var textRange; var j=0;
      var table = $('#dailyDetailsTable').clone();
    
      table[1].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);
  }
  

  clocation_1(latlngObj,cb){
console.log(latlngObj);

  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=>{       
    console.log('resaddresscomingfromAPi',res);   
    if(res.message == "Address not found in databse"){
        latlngObj['startAddress'] = "NA"; 
      // cb(null,latlngObj);
        var latLng_1 = {
          lat :"0",
          long:"0"
        };
        if(latlngObj.end_lat){
          latLng_1 = {
            lat: latlngObj.end_lat?latlngObj.end_lat:0,
            long:latlngObj.end_long?latlngObj.end_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=>{
          console.log('resaddresscomingfromAPi',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.end_lat){
        latLng_1 = {
          lat: latlngObj.end_lat?latlngObj.end_lat:0,
          long:latlngObj.end_long?latlngObj.end_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=>{
        console.log('resaddresscomingfromAPi',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);
    }
  })

}





}
