import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { ContactService } from '../../contact.service';
import { MyaccountComponent } from '../../myaccount/myaccount.component';
import { environment } from '../../../environments/environment';
import { SearchFilterPipe } from '../../search-filter.pipe'


declare var google: any;
declare var $:any;
declare var html2canvas:any;
declare var pdfMake :any ; 
declare var _:any;
import * as moment from 'moment';

@Component({
  selector: 'app-ignition-report',
  templateUrl: './ignition-report.component.html',
  styleUrls: ['./ignition-report.component.scss']
})
export class IgnitionReportComponent implements OnInit {
  ignition_data: any =[];
  fs : any;
  ls : any;
  emailid : any;
  date1 = new Date();
  before:any;
  or : any;
  useridd :any;
  time :any;
  device_data:any;
  devicess:any;
  final:any;
  custtype:any;
  cust:boolean=false;
  Load : Boolean = false;
  date : any;
  devicesss:any;
  mb:any;
  logoutbut:boolean;
  dealer:boolean;
  text:any;
  option:any; 
  finall:any;
  Fromdate:any;
  todate:any;
  options=[];
  logo:any;
  superAdmin:Boolean = false;
  dev_url = environment.hostUrl;
  t:any;
  dataSelect:any;
  errorMsg: any;
  errorDialog: boolean=false;
  searchText:any;
  tabelObj:any; 
  tableFlag: boolean=true;
  identifier : String = "ignition_report";
  stoppage_data:any;
  arrival_time:any;
  departure_time:any;
  report_to_show =[];
  Durations:any;
  address_show:any;
  start_add_lat:any;
  start_add_long:any;
  uId:any;
  vName:any;
  deviceArr = [];
  constructor(private contactService: ContactService,private router: Router,public dialog: MdDialog) { 
    
  
  }

  ngOnInit() {
 
    // var fTime = new Date().setHours(0,0,0);
    // this.Fromdate = new Date(fTime);
    this.t = document.getElementById("download");
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    // this.testTable();
    // this.contactService.getDevice(this.emailid,this.useridd).subscribe(

    //   data => {
    //     this.devicesss = data
     
    //     this.finall = (this.devicesss.devices);

    //     for(let i=0;i<this.devicesss.devices.length;i++){

    //       if(this.devicesss.devices[i].type_of_device =="Tracker"){

    //         let a ={
    //           value : this.devicesss.devices[i].Device_Name,
    //           viewValue:this.devicesss.devices[i].Device_Name,
    //           did:this.devicesss.devices[i].Device_ID,
    //           id:this.devicesss.devices[i]._id,
    //           user:this.devicesss.devices[i].user,
    //           email: this.devicesss.devices[i].Email_ID,
    //           deviceType: this.devicesss.devices[i].type_of_device
    //         }
    //         this.options.push(a);
    //       }

    //     }
    //       // console.log("ignition option",this.options);
    //       // let that = this;
    //       // setTimeout(()=>{
    //       //   that.loadropdown();
    //       // },100)  
      
    //   });

      if(this.custtype == true){
        this.cust = true;
      }  
      if(this.mb.charAt(0)=="n"){
        this.mb = ' '
      }

      if( window.localStorage['Custumer'] == 'ON'){
        this.logoutbut = false
        this.dealer = true
     }
     else{
         this.logoutbut = true
     }
          
     this.logo=window.localStorage['logo'];
     this.text=window.localStorage['text'];
    //  var fDate:any;
    //  var tDate:any;
    //  this.ignition_report(fDate,tDate);
    this.testTable();
  
    
     
  }

  // loadropdown() {
  //   let that = this;
  //   var script = document.createElement("script");
  //   script.setAttribute("type", "text/javascript");
  //   script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
  //   document.getElementsByTagName("head")[0].appendChild(script);
  //   setTimeout(() => {
  //     $('#select').multipleSelect({
  //       width: 200,
  //       placeholder: 'Select Vehicle.....',
  //       filter: true,
  //     })
  //    // $('#select').show();
  //   }, 100);


  // }

//   ign(){
//     this.router.navigateByUrl("device-report/ign-report");
//   }

//   ideal(){
//     this.router.navigateByUrl("device-report/ideal-report");
//   }
//   geo(){
//     this.router.navigateByUrl("geofencing");
    
//   }

//   notification(){
//     this.cond = false
//     this.router.navigateByUrl("notifications");
//   }

//   Ddetail(){
//     this.router.navigateByUrl("driverdetail");
//   }
//   DModel(){
//     this.router.navigateByUrl("deviceModel");
//   }
//   VType(){
//     this.router.navigateByUrl("VehicleType");
//   }
  
  
//   myaccount(){
   
//     let dialogRef = this.dialog.open(MyaccountComponent, {
//       width: '903px',
//       data: {}
//     });
  
//     dialogRef.afterClosed().subscribe(result => {
  
//       if(result == "succ"){
//         // console.log("Updated")
//       }
  
//     });
//   }
// openNav() {
//   /*  document.getElementById("myNav").style.width = "100%";
// */
//    this.router.navigateByUrl("location");

// }
// logout(){
//   window.localStorage.clear();
//   this.router.navigateByUrl("login");
// }
// devi(){
//   this.router.navigateByUrl("dashboard");

// }
// soon(){
//   this.router.navigateByUrl("const?_i="+window.localStorage.token);
  
// }
// new(){
//   this.router.navigateByUrl("new");
  
// }
// cond:Boolean = false;
// point : any = 0;
//  a(){
//   // console.log(this.point);
//    if(this.point == 0){
//     this.cond = true;
//     this.point ++;
//    }
//  else if(this.point % 2 == 0){
//   this.cond = true;
//   this.point ++;
//  }
//  else{
//    this.cond = false
//    this.point ++;
//  }

  
// }
// addcus(){
//   this.router.navigateByUrl("add");
// }
// report(){
//   this.cond = false
//   this.router.navigateByUrl("device-report");

// }

// route_map(){
//   this.router.navigateByUrl("routeMapping");

// }
// report_speed(){
//   // console.log("report speed call")
//   this.cond = false
//   this.router.navigateByUrl("device-report/device-speed-report");
// }
// mydealer(){
//   window.localStorage['token'] =  window.localStorage['Dealer_token'];
//   localStorage.removeItem('devices');
//   window.localStorage['DataUpdate'] = 'True';
//   if(window.localStorage['DataLoaded'] = 'True'){
//     window.localStorage['Custumer'] = 'OFF'
//     this.router.navigateByUrl("add")
//    // this.router.navigateByUrl("const?_status="+"OK");
//   }
// }


//   ignition_report(Fromdate,todate){
  
//     var deviceId;
//      this.deviceArr =  $('#select').multipleSelect('getSelects','value');
//       if(this.deviceArr.length==0){
//         deviceId=[];
//       }else{
//         deviceId= this.deviceArr;
//       }
//     let f_date = Fromdate.toISOString();
//     let t_date =  todate.toISOString();
//     this.contactService.ignitionReport(f_date,t_date,deviceId,this.uId)
//     // console.log(option);
//     this.uId =  this.useridd
//     this.report_to_show=[];
//     var outerThis = this;
//     this.Load = true;
 
//   this.contactService.ignitionReport(f_date,t_date,deviceId,this.useridd)
//   .subscribe(res=>{
//     this.ignition_data = res;
//     console.log('this.ignition_data',this.ignition_data); 
//     this.Load = false;
//     if(this.ignition_data.length==0){
//       this.errorDialog=true
//x        this.errorMsg="No data Available"
      
//     }else{
//       this.errorDialog=false;
//       if(this.tableFlag === true){
//         this.testTable(); 
    
//       }else{
       
//          this.tabelObj.clear();
//          this.tabelObj.rows.add(this.ignition_data); 
//          this.tabelObj.draw();      
       
//       }
//       this.tableFlag = false;

//     }
    
//     // console.log("ignition option",this.ignition_data);
//   },err=>{
//     this.Load = false;
//   })
   
// }
// XLurl:any;
// export_to_XL(Fromdate,todate,option){
  
//   // console.log("Excel report");
//   // console.log("thisisoption",option)
//   let f_date = Fromdate.toISOString();
//   let t_date = todate.toISOString();
//   this.uId = option.value;
//   // console.log(this.uId);
//   this.contactService.ignXLreport(f_date,t_date,this.uId,this.useridd)
//     .subscribe(res=>this.downloadXL(res)),
//                 error =>
//                  console.log("Error downloading the file."),
//                 () => console.info("OK");
//       // console.log(res);
//       // let filePath = res;
//       // this.XLurl= this.dev_url +"/"+res.filename;
//       // window.open(this.XLurl);
//       // this.t.href = this.XLurl;
//       // console.log(this.XLurl);
    

// }

// downloadXL(filepath){
//   // console.log(filepath.filename);
//   this.XLurl= this.dev_url+"/"+filepath.filename
//   // console.log(this.XLurl);
//   // var blob = new Blob(this.XLurl);
//   // this.url= window.URL.createObjectURL(blob);
//   window.location.href = this.XLurl;
// }
tab:any;
exportExcel()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    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, ""); // reomves input params

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

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

    return (sa);
}
optionVal:any;

// filterStates(val) {
//   if (val) {
//     const filterValue:any = val
//      this.dataSelect = this.options.filter( function(d){
//       return d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;    
//     });
//     return this.dataSelect;
//   }
// }
// autocompleteSearchObject = function autocompleteSearchFilter(err: any,searchResult:string){
//   console.log("Inside function");
// }

addressLink = "";
getlink(report){
  // console.log("inside function");
  // console.log("report=>",report);
  var lat = report.lat?report.lat:0;
  var lng = report.long?report.long:0;
  this.addressLink =  'https://maps.google.com/?q=' + lat + ',' + lng;
  return this.addressLink ; 
}


getAdd(latitude,longitude){
  var latti =0;
  var longi = 0
  if(latitude != undefined){
    latti = latitude;

  }
  if(longitude != undefined){
    longi = longitude

  }
    return 'https://maps.google.com/?q='+ latti + ',' + longi ; 
}

// callfunction(): void {
//   // this.Load = true;
//   this.tabelObj.draw();
// }

getReport(event){
  
  console.log("inside function");
  if(event == 'getExcel'){
    this.exportExcel();
  }else{
    var deviceId: any;
    var tpdata = event ; 
    var that = this;
    var fd = new Date(tpdata.fromDate);
    var td  = new Date(tpdata.toDate);
    
    if(event.deviceArr.length==0){
      deviceId=[];
    }else{
      deviceId= event.deviceArr;
    }
    this.deviceArr = deviceId; 
  
    
    this.Fromdate = fd;
    this.todate = td;
     this.tabelObj.ajax.reload();  
    // this.tabelObj.draw();  
    // this.tabelObj.draw();
    // if(this.ajaxCount != 0){
 
    // }
    // this.ajaxCount = 1 ; 
  }
 
}



testTable() {
  const that = this;
  console.log("inside function");
  $(document).ready(function() {
     that.tabelObj = $('#deviceTable').DataTable({
    
          "processing": true,
          "searching": true, 
          pagingType: 'full_numbers',
          pageLength: 25,
          serverSide: false,
          "scrollY":'65vh',  
          "scrollCollapse": true,     
          lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
          ajax: (dataTablesParameters,callback) => {
            console.log('temptemptemptemptemp',dataTablesParameters);
              var deviceID;
              that.Load = true;
             
              // dataTablesParameters.find._u = that.useridd;
            
              // dataTablesParameters.find._u = user;

              // if(that.deviceArr.length != 0){
         
                // dataTablesParameters.find.vname = deviceId;
              // }
            // if (that.Fromdate) {
                // var fdate = new Date(that.Fromdate).toISOString()      
                // dataTablesParameters.find.f_date = fdate    
                // dataTablesParameters.find.f_date =  from_date;    
            // };

            // if (that.todate) {
              // var fdate = new Date(that.todate).toISOString()      
              // dataTablesParameters.find.t_date = fdate     
                // dataTablesParameters.find.t_date = to_date  ;
          // };
          // this.deviceArr = deviceId; 
         
            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
            }
            var suburl = "";
            suburl += "/notifs/ignitionReport?from_date=" + temp.from_date +'&to_date=' + temp.to_date + '&_u=' + temp.user;
            if(that.deviceArr.length != 0){  
              suburl +='&device='+that.deviceArr;
            }

            if((temp.from_date != undefined)&&(temp.to_date != undefined)){
              that.contactService.get(suburl).subscribe(resp => {   
                // console.log(ignReport.length);  
                
                // that.getWorkingHour(resp);
                that.Load = false;
                callback({data : resp });
            }, err => {   
              that.Load= false;    
              console.log("error",err) ;     
            });

            }else{
              let ta = [];
              that.Load = false;
              callback({data : ta });
            }
          
        },  
      
          "columns": [
              {
                  "data": "vehicleName",
                  "defaultContent": "",
                  "render": function(data, type, row) {
                      
                    return data?data : '';                  
                  }
              },
              {
                  "data": "switch",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    return data?data:'';        
                  }
              },
              {
                  "data": "timestamp",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var expDate = new Date(data);
                    return data ? (moment(expDate).format('llll')) : "";  
                
                  }
              }, 
        
              
            {
              "data": "address",
              "defaultContent": "_id",
              render: function(data, type, row) {        
                  let lat = row.lat;
                  let long = row.long;        
                  var addressLink = '<a href="https://maps.google.com/?q='+ lat +','+long +' "  target="_blank" title="Click to get vehicle last location"> <img height="20px" width="20px" src="../../../assets/image/addressICON.png"> </a>';            
                  if(data){
                    return data ;
                  }else{
                    return addressLink;     
                  }
              }
          }                       
          ],  
          "columnDefs": [
            { className: "dt-body-left", "targets": [ 0,1,2,3 ] },
            {
              "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 },
       
          ] 
      });

  });

}

getAddress(latLng){
  console.log(latLng);
  
}


exportPdf(){


  html2canvas(document.getElementById('deviceTable'), {
     onrendered: function (canvas) {
        var data = canvas.toDataURL();
        console.log(data);
        var docDefinition = {
            content: [{
                image: data,
                width: 1000
            }]
        };
        pdfMake.createPdf(docDefinition).download("Table.pdf");
    }
});


}

// getWorkingHour(resp){
//   console.log(resp);  
//   var data = resp ;
//   var finalObj = {};
//   var that = this;
//   var temp = {}, switchMap = { 'OFF': 'OFF-ON_time', 'ON': 'ON-OFF_time' }, switchParam = ['OFF', 'ON'];
//   var process = function (param, temp) {
//     // console.log('temp',temp);
//     for (var j = 0; j < param.length; j++) {
//       if (temp[0].switch == param[j]) {
//         if (!finalObj[data[i].vehicleName])
//           finalObj[data[i].vehicleName] = {};
//         if (temp.length == 2) {
//           if (!finalObj[data[i].vehicleName][switchMap[param[j]]])
//           finalObj[data[i].vehicleName][switchMap[param[j]]] = 0;
//           finalObj[data[i].vehicleName][switchMap[param[j]]] += new Date(temp[0].timestamp).getTime() - new Date(temp[1].timestamp).getTime();
//           // console.log('finalObj',finalObj);
//           // console.log(finalObj[data[i].vehicleName][switchMap[param[j]]]);

//           console.log('finalObj',finalObj);
//           temp.splice(0, 1);
//         }
//       }     
//     }
//   }
//   for (var i = 0; i < data.length; i++) {
//     if (!temp[data[i].vehicleName])
//     temp[data[i].vehicleName] = [];
//     temp[data[i].vehicleName].push(data[i]);
//     process(switchParam, temp[data[i].vehicleName]);
//   }
//     // console.log('finalObj',finalObj);

// }








}
