import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import {DialogContentExampleDialogComponent} from '../dialog-content-example-dialog/dialog-content-example-dialog.component'
/* import {Tab} from './tab'; */
import {Device} from '../device';

import {Driver} from '../driver';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as io from 'socket.io-client';
/* import { DeviceReportComponent } from '../device-report/device-report.component';
 */import { DeviceEditComponent } from '../dashboard/device-edit/device-edit.component';
import {MdSnackBar} from '@angular/material';
import { DeviceShareComponent } from '../dashboard/device-share/device-share.component';
import { ShareUserComponent } from '../dashboard/share-user/share-user.component';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {ContactService} from '../contact.service';
import { checkNoChangesNode } from '@angular/core/src/view/view';
import { SpeednotifyComponent } from '../dashboard/speednotify/speednotify.component';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import { ShowCaliberationComponent } from '../show-caliberation/show-caliberation.component';
declare var $: any;

declare var google: any;
declare var swal: any;

@Component({
  selector: 'app-vehicle-type',
  templateUrl: './vehicle-type.component.html',
  styleUrls: ['./vehicle-type.component.css'],
  providers: [ContactService,SidebarComponent]
})
export class VehicleTypeComponent implements OnInit {

  adbtn: string;
  chkAddBtn: string;
 //private url = 'http://localhost:3000/api/graph';  
  private socket;
  Load:boolean=false
 messages = [];
 connection;
 graphs:any;
 message;
  numberOfOnlineUsers: number;
devices: Device[];
device: Device;
iconType = {value:"",viewValue:""}
drivers:any=[];
driver:any=[];

vehicles:any=[];
vehicle:any=[];

Device_ID: string;
Serial_Num: string;
Manf: string;
Model: string;
del:boolean = false;
Des: string;
Hardware_Ver: string;
Loca: string;
login:any;  
visibility:any;
/* tabs: Tab[] = []; */
calculateResult=[];
value:any;
a:any;
homeVis:any;
visibility0:any;
j:any;
id:any;
dev:any;
checked:any
MdSlideToggleChange :any;
e: Event;
d:any;
  orgChk: any;
  calibrationTitle: any;
  noticeTitle: any;

myaccount(){
   
    this.cond = false
    this.router.navigateByUrl("accountSettings");
  // let dialogRef = this.dialog.open(MyaccountComponent, {
  //   width: '903px',
  //   data: {}
  // });

  // dialogRef.afterClosed().subscribe(result => {

  //   if(result == "succ"){
  //     console.log("Updated")
  //   }

  // });
}



// openDialog3(a,b){
//   let dialogRef = this.dialog.open(DeviceShareComponent, {
//     width: '528px',
//     data: { name: a , did:b}
//   });
calibrationData :any =[];
// columnGrid  = 'col-sm-12 col-md-12 col-lg-12';
// columnGrid_1 :any ;
openCaliberation(data){
  this.calibrationTitle = 'VOLTAGE CALIBRATION';
  this.noticeTitle = "Volatage Calibration";
  console.log('data',data);
  // let dialogRef = this.dialog.open(ShowCaliberationComponent,
  // {width:'280px',
  // data:data}) 
 this.calibrationData = data ; 
 if(this.calibrationData.length != 0){
  //  this.calibrationData = 'col-sm-9 col-md-9 col-lg-9';
  //  this.columnGrid_1  ='col-sm-3 col-md-3 col-lg-3';

}


}

opentempCaliberation(data){
  console.log('data',data);
  this.calibrationTitle = 'TEMPRATURE CALIBRATION';
  this.noticeTitle = "Temprature Calibration";
  // let dialogRef = this.dialog.open(ShowCaliberationComponent,
  // {width:'280px',
  // data:data}) 
 this.calibrationData = data ; 
 if(this.calibrationData.length != 0){
  //  this.calibrationData = 'col-sm-9 col-md-9 col-lg-9';
  //  this.columnGrid_1  ='col-sm-3 col-md-3 col-lg-3';

}


}
logout(){
  window.localStorage.clear();
  this.router.navigateByUrl("login");
}
soon(){
  this.router.navigateByUrl("const?_i="+window.localStorage.token);
  
}
addcus(){
  this.router.navigateByUrl("add");
}

Ddetail(){
  this.router.navigateByUrl("driverdetail");
}
DModel(){
  this.router.navigateByUrl("deviceModel");
}
VType(){
  this.router.navigateByUrl("VehicleType");
}
add_VehicleType(){
  this.router.navigateByUrl("addEditVehicleType");
}

table1ch(){
    
  myFunction();
      function myFunction() {
        var input, filter, table, tr, td, i,td1;
        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")[1];
          td1= tr[i].getElementsByTagName("td")[0]
          if (td) {
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
              tr[i].style.display = "";
            } 
            else if(td1.innerHTML.toUpperCase().indexOf(filter) > -1){
              tr[i].style.display = "";
            }
            else {
              tr[i].style.display = "none";
            }
          }       
        }
      }
    }
cond:Boolean = false;
point : any = 0;
 aa(){
  // 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 ++;
 }

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

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

}
report_speed(){
  // console.log("report speed call")
  this.cond = false
  this.router.navigateByUrl("device-report/device-speed-report");
}

summaryReport(){

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

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

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

}


vehicleRoute(){
  this.router.navigateByUrl("vehicleRoute");

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

}

dealerInfo(){
  this.cond = false
  this.router.navigateByUrl("dealerInfo");
}

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


}

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


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

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

}






BB:Boolean = false;
dataa:Boolean = false;



  


    devv:any;
 




delete(did){
  this.Load =true;
this.contactService.deldev(did)
.subscribe(
  data => {

    this.dev  = data 
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
  
      data => {
        this.devicess = data 
      
        this.final = (this.devicess.devices);
        this.Load =false
        this.tost1("delete");
        window.localStorage['DataUpdate'] = 'True';
        this.sidebar.sidebarData();     
      }, (err: any) => {
         
        // console.log(err);
      if(err.status !=   200)
      {
         this.Load =false
      }});

  }
 )



}


 adddev(){
  // console.log("Inside adddiv");
  //console.log(id);
this.router.navigateByUrl("add-device");
}



add_Driver(){
  // console.log("Inside adddiv");
  //console.log(id);
//this.router.navigateByUrl("addDriver");

this.router.navigate(["addDriver"],{queryParams :  {user_id : this.useridd}});

}
deleteRecord(data1){

  swal({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes, delete it!'
  }).then((result: { value: boolean; }) => {
    if (result) {
      this.contactService.deleteVehicleType(data1).subscribe(
        data => {
         this.vehicle=[];
         this.vehicles=[];
         this.getDriver();
         swal(
          'Deleted!',
          'Your file has been deleted.',
          'success'
        )
        },err=>{
          swal(
            'Server Error',
            'Error occured while deleting vehicle type , Please try after sometime !!!',
            'error'
          )
        });      
    }
  })


}



vewdev(id,name,type){

  // console.log("Inside adddiv");
 // console.log(id + name);
 var dataStatus = {
  vehicleId:id,
  vehicleName:name,
  vehicleType:type
}
  if(type=="Tracker"){

    this.router.navigateByUrl("location?_dname="+name+"_id="+id);
    window.localStorage['devDetail']= JSON.stringify(dataStatus);
    
    
  }
  else{
  this.router.navigateByUrl("account?_did="+id+"."+name); 
  }
}

  selectedIndex:number=0;
  clickMe(value){
    this.selectedIndex=this.value;
    if(!this.visibility0)
    this.visibility0=!this.visibility0; 
  }

  onLinkClick($event: any) {
    // console.log($event);
  
  }
/*   addTab() {
    var tab = new Tab();
    this.tabs.push(tab)
  }  */
  cancle(a){
    // console.log(a);   
    this.visibility0=!this.visibility0;  
  }
  
  constructor(public sidebar :SidebarComponent,public dialog: MdDialog,public snackBar: MdSnackBar,private router: Router, private contactService: ContactService, private activatedRoute: ActivatedRoute) { 
   
  }

sha :any;

myInput:any;
data_descip :any;
before:any;
// TOAST

tost1(divid){
if(divid == "share"){
  this.data_descip = "Device Succesfully Shared";
  launch_toast();
}
else if(divid == "delete"){
  this.data_descip = "Device Deleted Succesfully";
  launch_toast();
}
else if(divid == "update"){
  this.data_descip = "Device Succesfully Updated";
  launch_toast();
}
else if(divid == "blankemail"){
  this.data_descip = "Blank Email ID or Mobile Number";
  launch_toast();
}
else if(divid == "deleteshareDevice"){
  this.data_descip = "Share Device Succesfully Removed";
  
  launch_toast();
}
else if(divid == "removeuser"){
  this.data_descip = "Share Device User Succesfully Removed";
  
  launch_toast();
}



else if(divid == "No_Dev"){
  this.data_descip = "No Shared Users for this Device";
  
  launch_toast();
}
else if(divid == "device_alert"){
  this.data_descip = "Speed Alert Sucessfully Added";
  launch_toast();
}
else if(divid == "NotSucc"){
  this.data_descip = "Speed Alert Removed";
  launch_toast();
}
else if(divid == "new_Device"){
  window.localStorage['FinalAddDevice'] = 'False'
  this.data_descip = "New Device Added";
  launch_toast();
}
  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", ""); }, 1500);
}
 }


  shareOwner:any;
  ss:any;
  y:any;




fs :any;
ls :any;
or :any;
/* e =[];
 */token :any;
emailid :any;
devicess :any;
devicesss :any;
userID:any;
final:any;
lat:any;
lng:any;
latLongArr:any
convertedToString :String;
useridd:any;
notifi = [];
g:any;

/* notify(){
  $(document).ready(function()
  {
  $("#notificationLink").click(function()
  {
  $("#notificationContainer").fadeToggle(300);
  $("#notification_count").fadeOut("slow");
  return false;
  });

  //Document Click hiding the popup 
  $(document).click(function()
  {
  $("#notificationContainer").hide();
  });

  //Popup on click
  $("#notificationContainer").click(function()
  {

  return false;
  });

  });
} */
custtype:any;
cust:boolean=false;

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");
  }
}
getdev(){
  let foods = []
  this.contactService.getDevice(this.emailid,this.useridd).subscribe(
      
    data => {
      this.devicess = data 
      this.final = this.devicess.devices
      // console.log(this.final);
      
     for(let i=0;i<this.devicess.devices.length;i++){
     
      //  if(this.devicess.devices[i].type_of_device =="Tracker"){
         let a ={
          value : this.devicess.devices[i].Device_Name,
          viewValue:this.devicess.devices[i].Device_Name
         }
         foods.push(a);
      //  }
    
     }

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

}
mb:any;
logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
data_to_view=[];
Durations:any;
superAdmin:Boolean = false;


report_map(){
  this.router.navigateByUrl("routeMapping");

}


  ngOnInit() {


    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.orgChk = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOrganisation ; 
    this.adbtn = localStorage.getItem("dlrchk")
    console.log(this.orgChk);
    
   this.logo=window.localStorage['logo'];
   this.text=window.localStorage['text'];  
    window.localStorage['DataUpdate'] = 'True'
    if( window.localStorage.FinalAddDevice == 'True'){
      this.tost1("new_Device");
    }
    this.sidebar.sidebarData();
 
    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;
    // console.log("abc", this.custtype);
    //this.getdev();
    if(this.custtype == true){
      this.cust = true;
    }  
         let  foods = [ ];

         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'];

 /*    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
      
      data => {
        this.devicess = data 
  


        this.final = this.devicess.devices
        
       for(let i=0;i<this.devicess.devices.length;i++){
       
         if(this.devicess.devices[i].type_of_device =="Tracker"){
           let a ={
            value : this.devicess.devices[i].Device_Name,
            viewValue:this.devicess.devices[i].Device_Name
           }
           foods.push(a);
         }
      
       }
  
      }); */
/*       sidebarData */
      var retrievedData = localStorage.getItem("devices");
      var cord = JSON.parse(retrievedData);
      this.final = cord; 
      console.log("this.final",this.final);
   
      if(this.final == null){
        console.log("No data available");

      }else{
        for(let i=0;i<this.final.length;i++){
          if(this.final[i].type_of_device =="Tracker"){
            let a ={
             value : this.final[i].Device_Name,
             viewValue:this.final[i].Device_Name
            }
            foods.push(a);
          }     
        }
      }
      this.getDriver();

  }

  getDriver(){

    this.contactService.getVehicleType(this.useridd).subscribe(
          
      data => {
       // this.drivers = data 
       /*  this.final = this.devicess.devices[0]; */
        console.log("DATA",data);
      //  console.log("The data of the Drivers"+this.vehicles);

        

       for(let i=0;i<data.length;i++){
        this.vehicle.push(data[i]);
        //  console.log( this.vehicle);
      
        }
  
      });
      
  }
/*   this.socket = io.connect('https://13.126.36.205:5000');
  this.socket.on('connect', function(){
    console.log("IO Connected");
  
  }); */
  deviceData=[];
  arrival_time:any;
  baba=[]
  status_toShow:any;
  address_show:any;
  lattitude:any;
  longitude:any;
  
  //  abc(div){
    
  //   this.baba=[]
  //   this.deviceData=div;
  //   var outerThis = this;
  //   var start_add:any;
    
  
   
  //     var i = 0, howManyTimes = this.deviceData.length;
  //     // console.log(this.deviceData.length);
  //     function f() {
  //     //   console.log("ABC");
  //     //   outerThis.arrival_time = new Date(outerThis.deviceData[i].status_updated_at)

  //     //   let  dev_status= outerThis.deviceData[i].status;
         
      
  //     //     var curr_time= new Date();
  //     //     var fd = new Date(outerThis.arrival_time).getTime();
  //     //     var td = curr_time.getTime();
  //     //     var timedev_status_difference = td-fd;
  //     //     var total_min = timedev_status_difference/60000;
  //     //     var hours = total_min/60
  //     //     var rhours = Math.floor(hours);
  //     //     var minutes = (hours - rhours) * 60;
  //     //     var rminutes = Math.round(minutes);
        
  //     //     outerThis.Durations = rhours + " "+'hrs'+ " " +  rminutes + " " + 'min';
  //     //     console.log(outerThis.Durations);   
          

  //     //     if(dev_status==undefined){
            
  //     //       outerThis.status_toShow = "NA";

  //     //     }else{
  //     //       outerThis.status_toShow = dev_status + " " + "Since" +" "+ outerThis.Durations;
  //     //     }
    
  //     //     outerThis.deviceData[i].status  =  outerThis.status_toShow ;
  //     //     debugger;
  //     //     if(outerThis.deviceData[i].last_location==undefined){
  //     //       outerThis.lattitude = null;
  //     //       outerThis.longitude = null;
  //     //     }else{
      
  //     //       outerThis.lattitude = outerThis.deviceData[i].last_location.lat;
  //     //       outerThis.longitude = outerThis.deviceData[i].last_location.long;
  //     //     }
      
  //     //    console.log(outerThis.lattitude,outerThis.longitude);
  //     //     var geocoder = new google.maps.Geocoder();
  //     //     var latlng = new google.maps.LatLng(outerThis.lattitude,outerThis.longitude);
    
  //     //     var request = {
  //     //       latLng:latlng
  //     //     };
          
        
  //     //     debugger;
  //     //     geocoder.geocode(request, function(data,status){
  //     //       if(status == google.maps.GeocoderStatus.OK){
  //     //         if(data[0]!=null){                            
  //     //            outerThis.address_show = data[0].formatted_address; 
  //     //            outerThis.deviceData[i].Location = outerThis.address_show;
  //     //            console.log(outerThis.address_show);               
  //     //         }else{
  //     //           console.log("No address available")
  //     //           outerThis.address_show = "No address available";               
  //     //         }  
  //     //       }
  //     //       else{      
          
  //     //         outerThis.address_show = 'NA';
  //     //         outerThis.deviceData[i].Location = outerThis.address_show;
  //     //         console.log(outerThis.address_show);
  //     //       } 
  //     //       i++;
  //     //     })  
  //     // if( i < howManyTimes ){
  //     //     setTimeout( f,2000 );
         
  //     // }
  //   }
  //   if(howManyTimes)
  //     f();
    
  
  // //  console.log(outerThis.deviceData);

  //  } 
 


   edit_Record(data){
    //  console.log(id);
    console.log("DATA=>",data.iconType);
    
     
     localStorage.setItem("vehType",JSON.stringify(data));
     this.router.navigateByUrl("editVehicle_type");
   }

}
