import { Component, OnInit, OnDestroy,Output,EventEmitter } from '@angular/core';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {DatainjectionService} from '../datainjection.service'
import * as CryptoJS from 'crypto-js';
import {ContactService} from '../contact.service';
import * as io from 'socket.io-client';
import * as jquery from 'jquery';
import {Observable} from 'rxjs/Rx';
declare var _:any,$:any;
@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  providers:[ContactService]
})
export class SidebarComponent implements OnInit, OnDestroy{
 
  
timer:any  = Observable.timer(100, 100);
add_dev:boolean;
subscription:any
groupData:any={};
  groupId: any;
  DealerID: any;
  superAdmin: any;
  supAdm: any;
refresh()
{
 this.subscription = this.timer.subscribe(t => {
    this.Ing_Status();
  });
}

//this.subscription = this.timer.subscribe(t => {
  skip:any;
  limit:any;
  search:any;
  sidebarData(){
      if(this.checker == "OK" || this.checker == "ok"){
        this.injectData.getData(this.emailid,this.useridd,this.groupId,this.skip,this.limit,this.search,this.supAdm,this.DealerID).subscribe(
          (data) => {
            // this.Load=false;
            this.devicess = data
            this.final = this.devicess.devices
           

            this.total_final = this.final
            console.log(this.final,"-------------------------------->")
            if(this.final.length == 0 ||this.final == null || !this.final){
              this.add_dev = false
              console.log("Load1");
              // this.Load=false;
            }
            else{
              this.add_dev = true
            }
            this.Ing_Status();
          //  this.refresh();
            let val = JSON.stringify(this.final);
            localStorage.setItem("devices",val);
            window.localStorage['LoadGraph'] = 'True'
            window.localStorage['checker'] = 'Data'
            window.localStorage['DataLoaded'] = 'True'

           // window.localStorage['GetDevData'] = 'False'
          
           
          //  this.table();
          //  this.subscription.unsubscribe();
          },
          (err)=>{
            if(err){
              console.log("Load3");
              // this.Load = false;
            }
          }
        )
       }
       else if( window.localStorage.DataUpdate == 'True'){
 
        
        this.final = []
        this.injectData.getData(this.emailid,this.useridd,this.groupId,this.skip,this.limit,this.search,this.supAdm,this.DealerID).subscribe(
          (data) => {
            this.devicess = data 
            this.final = this.devicess.devices
            console.log("7444444444444",this.final);
            
            this.total_final = this.final
            if(this.final.length == 0 ||this.final == null || !this.final){
              this.add_dev = false
              console.log("Load3");
              // this.Load=false;
            }
            else{
              this.add_dev = true
            }
            this.Ing_Status();
          //  this.refresh();

            let val = JSON.stringify(this.final);
            localStorage.setItem("devices",val);
            window.localStorage['DataUpdate'] = 'False'
            window.localStorage['LoadGraph'] = 'True'
            window.localStorage['DataLoaded'] = 'True'

        //    window.localStorage['GetDevData'] = 'False'
           // this.subscription.unsubscribe();
           console.log("Load4");
            // this.Load=false;
          //  this.table();
         //   this.subscription.unsubscribe();

          },
          (err)=>{
            if(err){
              console.log("Load5");
              // this.Load = false
            }
          }
        )
       }
       else if(this.checker == "Data"){
        var retrievedData = localStorage.getItem("devices");
        var cord = JSON.parse(retrievedData);
        this.final = cord  
        this.total_final = this.final
        if(this.final.length == 0 ||this.final == null || !this.final){
          this.add_dev = false;
          console.log("Load6");
          // this.Load=false;
        }
        this.total_final = this.final
        window.localStorage['DataLoaded'] = 'True'
        this.Ing_Status();
      //  this.refresh();

      //  this.subscription.unsubscribe();
      //  window.localStorage['GetDevData'] = 'False'
      console.log("Load7Side");
        // this.Load=false;
       // this.table();
       // this.subscription.unsubscribe();

      }

       else{
        this.injectData.getData(this.emailid,this.useridd,this.groupId,this.skip,this.limit,this.search,this.supAdm,this.DealerID).subscribe(
         (data)=> {
            this.devicess = data 
            this.final = this.devicess.devices
            this.total_final = this.final;
            if(this.final.length == 0 ||this.final == null || !this.final){
              this.add_dev = false
              console.log("Load8");
              // this.Load=false;
            }
            else{
              this.add_dev = true
            }
            this.Ing_Status();
            //this.refresh();

            let val = JSON.stringify(this.final);
            localStorage.setItem("devices",val);
            window.localStorage['LoadGraph'] = 'True'
            window.localStorage['checker'] = 'Data'
            window.localStorage['DataLoaded'] = 'True'

        //    window.localStorage['GetDevData'] = 'False'
        console.log("Load9");
            // this.Load=false;
           // this.subscription.unsubscribe();
           // this.table();
         //   this.subscription.unsubscribe();

          },
          (err)=>{
            if(err){
              console.log("Load10");
              // this.Load = false;
            }
          }
        )
       }
     //  console.log(this.final)
 //   }

 // })
   
  }

  specific:any
  mb:any
  constructor( private contactService: ContactService,private router: Router,private injectData:DatainjectionService) { 
    // this.table();
    window.localStorage['GetDevData'] = 'True'

      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;
      if(this.custtype == true){
        this.cust = true;
      }  
      if(this.mb.charAt(0)=="n"){
        this.mb = ' '
      }
 
    this.socket_Ing = this.injectData.getSocket_gps();
      //io.connect('https://www.oneqlik.in/gps', { secure: true, rejectUnauthorized: false, transports: ["polling"], upgrade: false });
              
    this.socket_Ing.on('connect', function(this){
   
    });
//  this.Load = true;
    
  // var secretKey = 'adnateIOTtrackeR';
   this.checker = window.localStorage.checker
  // console.log(this.checker)
    this.sidebarData();
  }
  try:any
  devicess:any;
  final:any = null;
  userID:any;
  fs:any;
  ls:any;
  or:any;
  emailid:any;
  useridd:any;
  custtype:any;
  cust:boolean = false;
  // Load:boolean = false;


  openNav() {
    /*  document.getElementById("myNav").style.width = "100%";*/
    window.localStorage['Device_detail'] = this.devicess;
     window.localStorage['mapLoad_ID'] = "True"
     this.router.navigateByUrl("location");
    //  this.router.navigateByUrl("fuelComp");
  }
  showButton=true;
  vewdev(id,name,type){
      this.contactService.menuReturnSet('openNav');
   var dataStatus = {
     vehicleId:id,
     vehicleName:name,
     vehicleType:type
   }
    if(type=="Tracker"){
      window.localStorage['mapLoad_ID'] = id;
      window.localStorage['mapLoad_Name'] = name
      window.localStorage['devDetail']= JSON.stringify(dataStatus);
      this.router.navigateByUrl("location");
    
    
/*       window.location.reload();
 */      
    }
    else{
  // debugger;
    this.router.navigateByUrl("account?_did="+id+"."+name); 
    }
  }
 img_URL :any 
 ing_Arr = []
 imgurl:any;
 text:any;
 myInput:any;
 total_final:any;
 test(a,b){
   //let b = a.split("|")[0]
   if(!a){
    this.imgurl="../../assets/image/ignition-idle.png";
    return true;
   }
   else if(a=="1"){
     this.imgurl="on";
     this.text = "Ignition Status: ON | Last Updated: "+b
     return true;
   }
   else if(a=="0"){
   
    this.imgurl="off"
    this.text = "Ignition Status: OFF | Last Updated:"+b

    return true;
   }
   else{
  
   
    return false;
   }
 }


 statListener(index,dev)
 {
  var outerThis = this;
  var avgspd = "Average_Speed";
  var dst ="Distance";

  return function(stat,did){
  

    dev[avgspd] = stat.avgSpeed ? stat.avgSpeed.toFixed(2) : 0.00;

    dev[dst] = stat.distance;

    var passtodayOdo = dev[dst];
  
    var i = outerThis.final.indexOf(index);
    outerThis.final[i] = dev;
    outerThis.total_final = outerThis.final;
 
    window.localStorage['LoadGraph'] = 'True'
    let val = JSON.stringify(outerThis.final);
    localStorage.setItem("devices",val);
    window.localStorage['LoadGraph'] = 'True'
   
  }
 }
accListener(index,dev){

  var outerThis = this;
  var ing

   return function(acc,from,time,d4,d5){
   //  dev = d4;
    
    var newNum = "Ignition";
    var newTitle ="Ignition_Time"

    // var batteryStatus = "batteryStatus";
    // var gsmSignal = "gsmSignal";
    // var ignitionLock = "ignitionLock";
    // var gpsTracking = "gpsTracking";
    // var alarm = "alarm";
    // var power = "power";
    // var activated = "activated";
    // var satellites = "satellites";

    var newVal = acc;
    //var newTim = time;
    var dt = new Date(time);
      let  day = dt.getDate(); 
       let  month = dt.getMonth()+1; 
       let  year = dt.getFullYear();
     
       let final_date = day+"/"+month+"/"+year
      let tm = new Date(time).toLocaleTimeString();
   
      let total = final_date + " " + tm

 
    outerThis.ing_Arr.push(from)
    dev[newNum] = newVal;
    dev[newTitle] = total;
    var i = outerThis.final.indexOf(index);
    outerThis.final[i] = dev;
    outerThis.total_final = outerThis.final;
   // window.localStorage['DataUpdate'] = 'True'
    window.localStorage['LoadGraph'] = 'True'
    //outerThis.sidebarData();   
   // console.log(outerThis.total_final)
    let val = JSON.stringify(outerThis.final);
    localStorage.setItem("devices",val);
    window.localStorage['LoadGraph'] = 'True'

  }

}


ind :any
gh = []
table(){
  
  makeTableScroll();
  function makeTableScroll() {
    var $table = $('table.scroll'),
    $bodyCells = $table.find('tbody tr:first').children(),
    colWidth;

// Adjust the width of thead cells when window resizes
$(window).resize(function() {
    // Get the tbody columns width array
    colWidth = $bodyCells.map(function() {
        return $(this).width();
    }).get();
    
    // Set the width of thead columns
    $table.find('thead tr').children().each(function(i, v) {
        $(v).width(colWidth[i]);
    });    
}).resize(); 
}
}


Ing_Status(){
 this.ing_Arr = []
 
  for(var y=0; y<this.final.length; y++){
    // this.socket_Ing.emit('acc',this.final[y].Device_ID )
    this.socket_Ing.on(this.final[y].Device_ID+'acc', this.accListener(y,this.final[y]))
    // this.socket_Ing.on(this.final[y].Device_ID+'acc',function(d1,d2,d3,d4,d5){
    //   console.log("d1,d2,d3,d4,d5",d1,d2,d3,d4,d5);
    // });
    var d = new Date();
    var a = d.setHours(0,0,0,0)

    // this.socket_Ing.emit('stat',this.final[y].Device_ID,this.final[y].Device_Name,a,null)
    // this.socket_Ing.on(this.final[y].Device_ID+'stat',this.statListener(y,this.final[y]))
    /* let val = JSON.stringify(this.final);
    
    localStorage.setItem("devices",val); */
  }
}

  table1ch(){
    myFunction();
        function myFunction() {
          var input, filter, table, tr, td, i;
          input = document.getElementById("myInput");       
          filter = input.value.toUpperCase();
          table = document.getElementById("myTable");
          tr = table.getElementsByTagName("tr");
          for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
              if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
              } else {
                tr[i].style.display = "none";
              }
            }       
          }
        }
      }
      checker:any;
      dev:any;
     
      private socket_Ing
      private socket_stat
   da :any   
   
getrequest(para){

  this.da = para
  this.specific = true
  // this.sidebarData()
 // console.log(this.total_final)
}

  ngOnInit() {

    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;

    if(this.custtype){
      this.DealerID = this.useridd
    }
    if(this.superAdmin){
      this.supAdm = this.useridd;
    }

   let socket_Ing = this.injectData.getSocket_gps();
    io.connect('https://www.oneqlik.in/gps', { secure: true, rejectUnauthorized: false, transports: ["websocket", "polling"], upgrade: false });
            
    socket_Ing.on('connect', function(this){
 

  });


    // this.injectData.getGroupData(this.emailid,this.useridd).subscribe(resp=>{
    //   this.groupData = resp.map(function(d){
    //     d.vehicleDetails.map(function(d1){
    //       debugger;
    //       socket_Ing.emit('acc',d1.Device_ID )
    //       socket_Ing.on(d1.Device_ID+'acc',()=>{
    //         return function(ind,data){
    //           console.log("451",data);
    //           d1= data;
    //         }
    //       })
    //       socket_Ing.emit('stat',d1.Device_ID,d1.Device_Name,new Date().setHours(0,0,0,0),null)
    //       socket_Ing.on(d1.Device_ID+'stat',()=>{
    //         return function(ind,data){
    //           debugger;
    //           console.log("459",data);
    //           d1=data;
    //         }
    //       })
    //       return d1;
    //     })
    //   return d;
    //    })
    // });
  }
  ngOnDestroy() {
    for (var e = 0; e <  this.ing_Arr.length; e++){
      // console.log(this.ing_Arr[e])
      
     this.socket_Ing.removeAllListeners(this.ing_Arr[e])
    }
   this.socket_Ing.removeAllListeners()
  }
        
  showd(d){

      d.flag =!d.flag;
  }
  show(d){

    if(d.flag == undefined)
      d.flag = true;	
    else
      d.flag = !d.flag; 
  }


  // filter
 

  //sorting
  key: string = 'Device_Name'; //set default
  reverse: boolean = false;
  sort(key){
    // console.log(key);
    this.key = key;
    this.reverse = !this.reverse;
  }

  searchFilter(){
    this.myInput;
    // console.log(this.myInput);
    // this.sidebarData()

  }


}
