import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ContactService } from '../../contact.service';
declare var $: any, DataTable: any;
import * as moment from 'moment';
declare var swal: any;
@Component({
  selector: 'app-device-sosreport',
  templateUrl: './device-sosreport.component.html',
  styleUrls: ['./device-sosreport.component.scss']
})
export class DeviceSOSreportComponent implements OnInit {
  option:any;
  Fromdate:any = new Date();
  todate:any= new Date();
  dataSelect: any;
  useridd: any;
  t: any;
  devicesss: any;
  finall: any;
  emailid: any;
  options: any=[];
  Load: boolean;
  tabelObj: any;
  DealerId: any;

  constructor(private contactService: ContactService,private router: Router) { }
   
  ngOnInit() {
      console.log(this.Fromdate.setHours(0,0,0));
   //  var from = new Date()
    // this.Fromdate = from.setHours(0,0,0);
    // console.log(this.Fromdate);
    this.t = document.getElementById("download");
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.DealerId = JSON.parse(window.atob(window.localStorage.token.split(".")[1]));
    console.log("oifjerteoimfspferkrepofwe,rpewrekewpoewerkewop",this.DealerId);
    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);
      });
      this.testTable();
  }

  callfunction(): void {
    this.tabelObj.draw();
}


  filterStates(val) {
    // console.log(val)
    // console.log(this.options)
    if (val) {
      const filterValue:any = val
       this.dataSelect = this.options.filter( function(d){
    
        return d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;    
      });
      return this.dataSelect;
    }
  
  }


  // exportExcel(){

  // }

    // ======================================SOS ALERT by data Table ====================================

    testTable() {
      const that = this;

      $(document).ready(function() {
          that.tabelObj = $('#deviceTable').DataTable({
              serverSide: true,
              "processing": true,
              "searching": false,
              "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],

              ajax: (dataTablesParameters: any, callback) => {

                  dataTablesParameters.op = {};
                  dataTablesParameters.select = [];
                  dataTablesParameters.find = {};


                  // console.log(dataTablesParameters);
                  // console.log("callback", callback);

                  // dataTablesParameters.find = {
                  //   _id: that.useridd         
                  // };
                  dataTablesParameters.columns = [
                      { data: "_id" },
                      { data: "device" },
                      { data: "vehicleName" },
                      { data: "timestamp" },
                      { data: "address" }
                   
                    ]
                  
                      dataTablesParameters.find.user = that.useridd;
                      dataTablesParameters.find.type = 'SOS';

                 
                  if (that.deviceArr.length != 0) {
                       console.log(that.dataSelect);
                      dataTablesParameters.find.device = that.deviceArr[0];
                  }
                  if (that.Fromdate) {
                      
                      var fdate = new Date(that.Fromdate).toISOString();
                     
                      dataTablesParameters.find['timestamp'] = dataTablesParameters.find['timestamp'] ? dataTablesParameters.find['timestamp'] : {};
                      dataTablesParameters.find['timestamp']['$gte'] = fdate;       
                  };
                  // }
                  if (that.todate) {
                      var tdate =  new Date(that.todate).toISOString()
                      dataTablesParameters.find['timestamp'] = dataTablesParameters.find['timestamp'] ? dataTablesParameters.find['timestamp'] : {};
                      dataTablesParameters.find['timestamp']['$lte'] = tdate;
                  }

                  var suburl = "";
                  suburl += "/notifs/statusReport";
                  // console.log(suburl);
                  // console.log(dataTablesParameters);
                  // console.log(suburl)
                  that.Load = true;
                  that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
                    that.Load = false;
                    console.log(resp);
                    // if(resp.data.length == 0){
                    //   swal(
                    //     'Oops !!!',
                    //     'No data found',
                    //     'error'
                    //   )
                    // }
                      callback(resp);
                  }, err => {
                    that.Load =false;
                    swal(
                      'Error',
                      'Internal server error, Please try after somtime !!!',
                      'error'
                    )
                      // console.log(err);
                      // console.log(err.status);
                  });
              },
              "columns": [
                  {
                      "data": "device",
                      "render": function(data, type, row) {
                          return data ? data : "";
                      }
                  },
                  {
                    "data": "vehicleName",
                    "render": function(data, type, row) {
                        return data ? data : "";
                    }
                },
                  {
                      "data": "timestamp",
                      render: function(data, type, row) {
                        var created_time = new Date(data);
                        return data ? (moment(created_time).format('dddd,ll,LTS')) : "";
                      
                      }
                  },
                  {
                      "data": "address",
                      render: function(data, type, row) {
                          return data ? data : "";
                      }
                  }                        
              ],

              // columnDefs: [
               
              // ],

          });
          // $('#deviceTable tbody').on('click', 'button', function() {
          //   debugger;
          //     var data = that.tabelObj.row($(this).parents('tr')).data();
          //     console.log("button clicked");
          // });
      });

      

  }








    // ======================================SOS ALERT by data Table ====================================

    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>";
        // console.log('tab_text',JSON.parse(tab_text));
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    // tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    // tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your 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);
}

    deviceArr = [];
    identifier : any = 'device_sos_report';
    getReport(event){
      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; 
        console.log('this.deviceArr',this.deviceArr);
        
        this.Fromdate = fd;
        this.todate = td;
        console.log("b4");
        // this.tabelObj.clear();
        // var aa = [];
        // this.tabelObj.rows.add(aa); 
    
    
       
          // this.tabelObj.ajax.reload();    
        
        
          this.tabelObj.draw();         

        
         
          
      
      
      }
     
    }
    

  

}
