import { Component, OnInit } from '@angular/core';
import { ContactService } from './../contact.service';

declare var $: any, DataTable: any;
import * as moment from 'moment';

import { MdDialog } from '@angular/material';
import { GpsEditMasterComponent } from './gps-edit-master/gps-edit-master.component';
import { FlashMessagesService } from 'angular2-flash-messages';


@Component({
  selector: 'app-gps-master',
  templateUrl: './gps-master.component.html',
  styleUrls: ['./gps-master.component.scss']
})
export class GpsMasterComponent implements OnInit {
  Fromdate=new Date();
  todate=new Date();
  tabelObj: any;
  emailid: any;
  useridd: any;
  option: any;
  supadm: any;
  deviceObjwithName: any=[];
  deviceSelect1: any=[];
  
  identifier:String='gps_master';
  Load: boolean;
  super_admin : any;
  isDealer: any;
  dlrID: any;
  constructor(public contactService: ContactService,public dialog: MdDialog,private _flashMessagesService: FlashMessagesService) {
    this.Fromdate.setHours(0, 0, 0);
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.supadm = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.isDealer = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isDealer;
    if(this.isDealer == true){
      this.dlrID = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._id
  }
   
  }

  ngOnInit() {
    // this.getAllDevice();
    this.testTable();
  }

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


  testTable() {
    //console.log("initId=>",id);
    console.log('Inside testTable');
    const that = this;
    $(document).ready(function () {
      that.tabelObj = $('#gpsTable').DataTable({
        "serverSide": true,
        "processing": true,
        "searching": false,
        "scrollX": true,
        "scrollY": "480px",
        "scrollCollapse": true,
        "responsive" :true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        ajax: (dataTablesParameters: any, callback) => {
          console.log('inside ajax call');
          dataTablesParameters.op = {};
          dataTablesParameters.select = [];
          dataTablesParameters.find = {};


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

          // dataTablesParameters.find = {
          //   _id: that.useridd         
          // };
          dataTablesParameters.columns = [
            {data : "_id"},
            { data: "imei" },
            { data: "date" },
            { data: "latDecimal" },
            { data: "longDecimal" },
            { data: "insertionTime" },
            {data : 'syncedAt'},
            {data : 'integrationResponse'},            
            { data: "speed" },
            {data:"ac"},
            {data : "currentFuel"},
            {data  : "raw"},
            { data: "ignition" },
            { data: "power" },
            {data : "fuelVoltage"},
            { data: "external_Battery" },
            { data: "powerCutAlarm" },
            { data: "satellites" },
            {data:'GPS positioned'},
            {data:'isFluctuation'},
            {data:'isPastData'},
          ]

       
            //  dataTablesParameters.find.supAdmin = that.useridd;
         

          if (that.deviceArr.length !=0) {
            // console.log(that.deviceSelect[0].id);
            dataTablesParameters.find.imei =that.deviceArr[0];
          }

        
          if (that.Fromdate) {
            console.log('that.Fromdate',that.Fromdate.toISOString());
            dataTablesParameters.find['insertionTime'] = dataTablesParameters.find['insertionTime'] ? dataTablesParameters.find['insertionTime'] : {};
            dataTablesParameters.find['insertionTime']['$gte'] = {
              _eval: 'date',
              value: new Date(that.Fromdate).toISOString()
            }
          };
          // }
          if (that.todate) {    
            that.todate.setSeconds(0);
            that.todate.setMilliseconds(0);
            console.log('that.todate',that.todate.toISOString())

            dataTablesParameters.find['insertionTime'] = dataTablesParameters.find['insertionTime'] ? dataTablesParameters.find['insertionTime'] : {};
            dataTablesParameters.find['insertionTime']['$lte'] = {
              _eval: 'date',
              value: new Date(that.todate).toISOString()
            };
          }



          // if(this.supadm){
          //   dataTablesParameters.find.supAdmin = that.useridd;
          // }

          var suburl = "";
          suburl += "/gps/datatable";
          // console.log(suburl);
          // console.log(dataTablesParameters);
          // console.log(suburl)
      //   if(id != 0)
            console.log('calling api');
        that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
          callback(resp);
        }, err => {
          // console.log(err);
          // console.log(err.status);
          callback({data:[]})
        });
    
         
        },
        "rowCallback": function(row: Node, data: any | Object, index: number){                    
          $('#delete', row).bind('click', () => {    
            // console.log("delete Method",data);
            var gpsId = data._id;
            that.contactService.deletegpsdata(gpsId)
              .subscribe(res=>{
                // console.log(res);
                that._flashMessagesService.show("Data Deleted", { cssClass: 'alert-warning', timeout: 2000 });
                that.callfunction();
              },err=>{
                that._flashMessagesService.show("Internal server error", { cssClass: 'alert-warning', timeout: 2000 });
                // console.log(err);
              })    
          });
          },

        "columns": [
          {
            "data": "imei",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "latDecimal",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "longDecimal",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "speed",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "date",
            "render": function (data, type, row) {

              var device_time = new Date(data);
              return data ? (moment(device_time).format('dddd,ll,LTS')) : "";
            }
          },
          {
            "data": "insertionTime",
            "render": function (data, type, row) {
              var created_time = new Date(data);
              return data ? (moment(created_time).format('dddd,ll,LTS')) : "";
            }
          },
          {
            "data": "syncedAt",
            "render": function (data, type, row) { 
              var insertion_time = new Date(data);
              return data ? (moment(insertion_time).format('dddd,ll,LTS')) : "";
            }
          }, 
          {
            "data": "integrationResponse",
            "render": function (data, type, row) {
              if(data)
              // alert(data);
              console.log(typeof(data));
              if(typeof(data) === 'object'){
                data = JSON.stringify(data);

              }
              return data ? data: "";
            }
          },      
          {
            "data": "ignition",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "power",
            "render": function (data, type, row) {
              return data ? data : ""
            }
          },
           {
            "data": "GPS positioned",
            "render": function (data, type, row) {
              return data ? data : ""
            }
          },
          {
            "data": "isFluctuation",
            "render": function (data, type, row) {
              return data ? data : ""
            }
          },
          {
            "data": "isPastData",
            "render": function (data, type, row) {
              return data ? data : ""
            }
          },
          {
            "data": "external_Battery",
            "render": function (data, type, row) {
              return data ? data : ""
            }
          },
          {
            "data": "fuelVoltage",
            "render": function (data, type, row) {
              return data ? (data/1000).toFixed(2) : ""
            }
          },
          {
            "data": "currentFuel",
            "render": function (data, type, row) {
              return data ? data : ""
            }
          },
          {
            "data": "raw",
            "render": function (data, type, row) {
              return data ? data : "" ; 
            }
          },
          {
            "data": "ac",
            "render": function (data, type, row) {
              return data ? data : ""
            } 
          },
          {
            "data": "powerCutAlarm",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "satellites",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data":null,"render":function(data,type,row){
            return '<i id="delete" class="fas fa-trash" style="cursor:pointer;color:red", title="Delete log"></i>'
        }}    
        ],
        "columnDefs": [
    
          { width: '20px', targets: ['15'] } 
        ]
      });
    });

  }

  deviceObj=[];



deviceSelect:any=[];
deviceName:any;
deviceName1:any;

  deviceArr=[];
  data_descip:any;

  getReport(event){  
    this.deviceArr=[];
    console.log("inside function",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);
      var Fromdate = fd.toISOString();
      var todate = td.toISOString();
 
      var diff = moment(todate).diff(Fromdate, 'days')
      // console.log(diff,"999999999");
      
      if(diff>=31){
         console.log('difference :' + diff)
          this.data_descip = 'Report is unavailable for more than a month';
          launch_toast();

      }else{
      if(event.deviceId.length==0){
        deviceId=[];
      }else{
        deviceId= event.deviceId;
      }
      this.deviceArr = deviceId;   
      this.Fromdate = fd;
      this.todate = td;
       this.tabelObj.ajax.reload();  
      }
    }
   
    function launch_toast() {
    // console.log(divid);
    var x = document.getElementById("toast")
    //console.log(x);
    x.className = "show";
    setTimeout(function () { x.className = x.className.replace("show", ""); }, 4500);
  }
  
}


  tab:any;
exportExcel()
{

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