import { Component, OnInit, Inject, ElementRef } from '@angular/core';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
declare var google :any;
declare var moment:any;

@Component({
  selector: 'app-trip-history',
  templateUrl: './trip-history.component.html',
  styleUrls: ['./trip-history.component.scss']
})
export class TripHistoryComponent implements OnInit {


  
  
  latlongObjArr: any;
  path: any;
  datee: any;
  dataArrayCoords: any=[];
  latLngLine: any=[];
  lat: any;
  lng: any;
  marker4: any;
  tempMapHistory=[];
  seekBarValue: any=200;
  sliderValue: number=0;
  start:any;
  flag: string;
  cummulative_Distance: number;
  ext_voltage: string;
  historyDate: any;
  indexValue: number;
  tdistance: any;
  triptime: any;
  constructor(public elementRef: ElementRef,public dialogRef: MdDialogRef<TripHistoryComponent>,@Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService) { }
  gMap:any;
//   Allow_Reverse: false
// Device_Id: "2049080054708"
// Device_Name: "siwitest"
// Planned_End_Time: "2021-09-09T08:17:00.132Z"
// Planned_Start_Time: "2021-09-08T08:17:00.132Z"
// Radius: 200
// Status: "ASSIGNED"
// deviceObjId: "612f33fa9e94de2c84f8278a"
// lrNumber: "4334"
// routeId: "613872f88d5eb72b9ce5bf58"
// total_odo: 0
// tripType: 1
  ngOnInit() {
    console.log('this.data.distance',this.data);
    this.tdistance = (this.data.distance/1000).toFixed(2)   + ' Kms.';
  console.log(this.data);
  var that= this;
    let map;
     if (navigator.geolocation) {  
       if(location.protocol != 'https:'){
         this.contactService.getlatLong().subscribe(res=>{
           console.log(res);
           var position = {
             coords: { 
               latitude: res.lat,
               longitude: res.lon
             }
           };
           this.gMap = new google.maps.Map(document.getElementById('map'), {
             center: {
                 lat: position.coords.latitude,
                 lng: position.coords.longitude
             },
           
             zoom: 18,
             mapTypeId: 'terrain'
         }); 
         this.plotPolyline();  
         if(that.data.geofences!=undefined){
             that.plotGeofence(that.data.geofences[0]._id);
             that.plotGeofence2(that.data.geofences[1]._id);
        }             
         })
        }else{
         navigator.geolocation.getCurrentPosition(function(position) {     
          that.gMap = new google.maps.Map(document.getElementById('map'), {
               center: {
                 lat: position.coords.latitude,
                   lng: position.coords.longitude
               },  
               zoom: 18,
               mapTypeId: 'terrain'
           });  
           that.plotPolyline();  
           if(that.data.geofences!=undefined){
            that.plotGeofence(that.data.geofences[0]._id);
            that.plotGeofence2(that.data.geofences[1]._id);
           }      
          });
       }    
      }  
    }

    
    plotPolyline(){
      this.sliderValue=0;
      var that = this;
      this.contactService.getCurrentLocation(this.data.Device_Id, this.data.Planned_Start_Time, this.data.Planned_End_Time).subscribe((data3) => {
        console.log(data3);
          this.latlongObjArr = data3;
          var flightPath = new google.maps.Polyline({
            geodesic: true,
            strokeColor: '#0000FF',
            strokeOpacity: 1.0,
            strokeWeight: 4,
            icons: [{
              icon: {
                strokeColor: '#056608',
                fillColor: '#056608',
                strokeOpacity: 0.8,
                strokeWeight: 4,
                path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
              },
              offset: '0',
              repeat: '100px'
            }         
            ],   
          });
          
          var playerSeekbar: any;
          $( document ).ready(function() {
            playerSeekbar = document.getElementById('slider1'); 
            console.log( "ready!", playerSeekbar['value']);
            playerSeekbar.oninput = function () { 
             
              zoomToObject(flightPath);
              that.changeRange();
               
            }
          });
      
          function zoomToObject(obj){
          var bounds = new google.maps.LatLngBounds();
          var points = obj.getPath().getArray();
          for (var n = 0; n < points.length ; n++){
              bounds.extend(points[n]);
          }
          that.gMap.fitBounds(bounds);
      }
          this.path = flightPath.getPath();
          var cumulativeDistance =0 ; 
       
          for (let i = this.latlongObjArr.length - 1; i > 0; i--) {
  
            var d_name = this.data.Device_Name;
            var speed = this.latlongObjArr[i].speed + "Km/hr";
            var im = this.latlongObjArr[i].Device_Id;
            
            // var speedArr.push(this.latlongObjArr[i].speed);
            // var heading = this.latlongObjArr[i].heading;
            // this.time = gmtDateTime.local().format('h:mm:ss A');
            this.datee = JSON.stringify(this.latlongObjArr[i].insertionTime);
            // //console.log(JSON.parse(this.datee));
            // var insTime = new Date(this.datee);
            this.datee = moment(JSON.parse(this.datee)).format('MMMM Do YYYY, h:mm:ss a');
            
            
            
            var content = '';
            content = '<div id="content"><div id="bodyContent"><div><br><b>DEVICE NAME : ' + d_name + '</b><br><b>IMEI : ' + im + '</b><br><b>DEVICE DATE : ' + this.datee + '</b><br><b>SPEED : ' + speed + '</b><br></div></b></div>'
            '</div></div>'
            
            if(this.latlongObjArr[i].isPastData != true){
              if(i === 0){
                cumulativeDistance += 0 ;
              }else{
                cumulativeDistance += this.latlongObjArr[i].distanceFromPrevious?parseFloat(this.latlongObjArr[i].distanceFromPrevious):0 ; 
              }       
              this.latlongObjArr[i]['cummulative_distance'] = (cumulativeDistance).toFixed(2) ;
            }else{
              this.latlongObjArr[i]['cummulative_distance'] = (cumulativeDistance).toFixed(2) ;
            }
  
            
            var arr = [];
            // //console.log(this.latlongObjArr[i].cummulative_distance);
            
            arr.push(this.latlongObjArr[i].lat);
            arr.push(this.latlongObjArr[i].lng);
            arr.push(this.latlongObjArr[i].speed);
            arr.push(this.latlongObjArr[i].cummulative_distance);
            arr.push(this.datee);
            arr.push(this.latlongObjArr[i].external_Battery);
            let cord = {
              lat: this.latlongObjArr[i].lat,
              lng: this.latlongObjArr[i].lng
            }
            this.dataArrayCoords.push(arr);
            
         
            
            this.latLngLine.push(cord);
            var iconSrc = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=S|00FF00|000000';
            var iconDest = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
            
            // ======================added ========================================
            // this.lat = this.latlongObjArr[i].lat;
            // this.lng = this.latlongObjArr[i].lng;       
            // this.path.push(new google.maps.LatLng(this.lat, this.lng));
  
            // =====================================added==============================
  
            if (this.latlongObjArr[i].interpolated == null || this.latlongObjArr[i].interpolated == undefined || this.latlongObjArr[i].interpolated.length == 0) {
              this.lat = this.latlongObjArr[i].lat;
              this.lng = this.latlongObjArr[i].lng;
              this.path.push(new google.maps.LatLng(this.lat, this.lng));
              
  
              // if (this.dataColor === true) {
              //   var markersPast = new google.maps.Marker({
                //     position: new google.maps.LatLng(this.lat, this.lng),
                //     icon: { path: google.maps.SymbolPath.CIRCLE, fillColor: fill_color, fillOpacity: 0.6, strokeColor: stroke_color, strokeOpacity: 0.9, strokeWeight: 5, scale: 2 },
              //     map: map,
              //   })
              
              //   markersPast['infowindow'] = new google.maps.InfoWindow({ content: content });
              
              
              //   google.maps.event.addListener(markersPast, 'click', function () {
                
                //     var lattitude = markersPast.position.lat();
              //     var longitude = markersPast.position.lng()  ;
              //     var latlng_1 =
              //     {
                //       "lat": lattitude,
                //       "long":  longitude
              //     }
              //     outerThis.contactService.getAddressByApi(latlng_1).subscribe(res=>{  
                
                //    if(res.message == "Address not found in databse"){ 
              //     var geocoder = new google.maps.Geocoder();
              //     var latlng = new google.maps.LatLng(lattitude, longitude);
              
              //     var request = {
                //       latLng: latlng
              //     };
              //     // //console.log('latlongVal', request)
              //     var innerThis = this ; 
              //     this['infowindow'].open(map, innerThis); 
              //     geocoder.geocode(request, function (data, status) { 
              //       if (status == google.maps.GeocoderStatus.OK) {
                //         if (data[0] != null) {
              //           // innerThis.contentAdd = data[0].formatted_address;
              //           var tempAdd = data[0].formatted_address;
              //             var getAddressContent = document.getElementById('addressBinding');
              //             getAddressContent.innerHTML = 'Address :' + tempAdd ;
                       
              
              //         } else {
                //           // //console.log("No address available")
              //           var tempAdd_1 = "No address available";
              //           var getAddressContent = document.getElementById('addressBinding');
              //           getAddressContent.innerHTML = 'Address :' +  tempAdd_1 ;
              
                     
              
              //         }
              //       }
              //       else {
                //         var tempAdd_2 = 'NA';
              //         var getAddressContent = document.getElementById('addressBinding');
              //         getAddressContent.innerHTML = 'Address :' +  tempAdd_2 ;
              //         //console.log('aaaaaaaaaaaaaa',getAddressContent);  
                    
              
              //       }
              
              //     })
              
              //       }else{
                //         var innerThis_1 = this ; 
                
                //         this['infowindow'].open(map, innerThis_1);      
              //         var tempAdd  = res.address ; 
              //         //console.log('innerThis_1.contentAdd',tempAdd);
              //         var chkTmout = setTimeout(function(){
              //           var getAddressContent = document.getElementById('addressBinding');
              //           // //console.log('getAddressContent',getAddressContent);
              //           getAddressContent.innerHTML = 'Address :' +   tempAdd  ;
              //           clearTimeout(chkTmout);
              //         },500)
              
              //       }
              
              //     })
              
              
                  
              //     })
              //   // cluster_arr.push(markersPast);
              
              // }
  
  
              var markerCurrent;
              var markerSrc;
              if (i == 1) {
                markerCurrent = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: that.gMap,
                  icon: iconDest
                });
                // outerThis.marker4  = markerCurrent;
                that.gMap.setCenter(new google.maps.LatLng(this.lat, this.lng))
                flightPath.setMap(that.gMap);
                zoomToObject(flightPath);
              }
              if (i == (this.latlongObjArr.length - 1)) {
                markerSrc = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: that.gMap,
                  icon: iconSrc
                });
  
                that.marker4 = markerSrc;
              }
              
              
            }
            else {
  
              for (let k = 0; k < this.latlongObjArr[i].interpolated.length; k++) {
                if (this.latlongObjArr[i].interpolated[k].location.latitude == null || this.latlongObjArr[i].interpolated[k].location.longitude == null) {
                  this.lat = this.latlongObjArr[i].lat;
                  this.lng = this.latlongObjArr[i].lng;
                } else {
                  this.lat = this.latlongObjArr[i].interpolated[k].location.latitude;
                  this.lng = this.latlongObjArr[i].interpolated[k].location.longitude;
                }
  
                this.path.push(new google.maps.LatLng(this.lat, this.lng));
                
                
                // if (this.dataColor) {
                  //   var markersPast = new google.maps.Marker({
                    //     position: new google.maps.LatLng(this.lat, this.lng),
                //     icon: { path: google.maps.SymbolPath.CIRCLE, fillColor: fill_color, fillOpacity: 0.6, strokeColor: stroke_color, strokeOpacity: 0.9, strokeWeight: 5, scale: 2 },
                //     map: map,
                //   })
                //   markersPast['infowindow'] = new google.maps.InfoWindow({ content: content }); 
                //   google.maps.event.addListener(markersPast, 'click', function () { 
                  //     //console.log("inside info window function 1");
                //     this['infowindow'].open(map, this); });
                
  
                // }
              }
              if (i == 1) {
                markerCurrent = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: that.gMap,
                  icon: iconDest
                });
                
                // outerThis.marker4 = markerCurrent;
                that.gMap.setCenter(new google.maps.LatLng(this.lat, this.lng))
                flightPath.setMap(that.gMap);
                zoomToObject(flightPath);
  
              }
              
              if (i == (this.latlongObjArr.length - 1)) {
                markerSrc = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: that.gMap,
                  icon: iconSrc
                })
                that.marker4 = markerSrc;
              }
            }
          }
          var tempData = {
            fromTime:this.data.Planned_Start_Time,
            toTime:  this.data.Planned_End_Time,
            device_name: this.data.Device_Id,
            device_obj: this.data.deviceObjId,
            lineThickness: 4,
            idleColor: 'red',
            parkingColor: 'blue',
            dataColor: 'green',
            flag: 'init'
          }
          tempData['dataArrayCoords'] = this.dataArrayCoords;
          this.seekBarValue = this.dataArrayCoords.length;
          this.tempMapHistory.push(tempData);
          console.log('this.tempMapHistory',this.tempMapHistory);
        })
     
        
      }

      zoomSet(){
        this.gMap.setZoom(15);
  }
  speed=200;
  changeSpeed(t){
    //console.log(t);
    this.speed = t * 100;
    var header = document.getElementById("myDIV");
    var btns = header.getElementsByClassName("sc-bdVaJa");
    for (var i = 0; i < btns.length; i++) {
      btns[i].addEventListener("click", function() {
      var current = document.getElementsByClassName("active");
      current[0].className = current[0].className.replace(" active", "");
      this.className += " active";
      });
    }
  }
  showStatus:boolean=false;
  goToPoint: () => void;
  moveMarker: () => void;
  play(playindex) {
    // //console.log('playindex',playindex);
  
    this.showStatus = true
    
    var icontype = this.data.iconType;
    var tempObj = { "icontype": icontype }
    var tempDataCoordArr = this.tempMapHistory[playindex].dataArrayCoords;
    
    tempObj["tempDataCoordArr"] = tempDataCoordArr;

    if (this.tempMapHistory[playindex]['flag'] == 'init') {
      this.animateMarker_history(this.marker4, tempDataCoordArr, 50, icontype);
      tempObj["marker"] = this.marker4;
      this.tempMapHistory[playindex]['flag'] = 'stop';
      tempObj["flag"] = this.tempMapHistory[playindex]['flag'];
 
    } else if (this.tempMapHistory[playindex]['flag'] == 'start') {
      
      this.moveMarker();
      // clearTimeout(this.start);
      this.tempMapHistory[playindex]['flag'] = 'stop';
      tempObj["flag"] = this.tempMapHistory[playindex]['flag'];
      
    } else
        if (this.tempMapHistory[playindex]['flag'] == 'stop') {
          this.speed = 0;
          clearTimeout(this.start);
          this.tempMapHistory[playindex]['flag'] = 'start';
          tempObj["flag"] = this.tempMapHistory[playindex]['flag'];
        }

    if (this.flag == 'reset') {
      this.marker4.setPosition({ lat: this.latLngLine[0].lat, lng: this.latLngLine[0].lng });
      this.flag = 'init';
    }

  }
  speeed2: any = 0;
  PlayData: boolean = false;
  playingHistory: boolean = false;
  rangeDetector:boolean=false;
  animateMarker_history(marker, coords, km_h, iconType) {
    this.cummulative_Distance = 0;
    //console.log('coords=>',coords);
    var ongoingMoveMarker = null;
    // this.SpeedMeter2 = true;
    // this.pauseDate = true;
    this.PlayData = true;
    // this.playingHistory = true;
    this.gMap.setZoom(15);
    if ((km_h == 0) || (km_h == '0')) {
      km_h = 50;
    }
    var map, marker;
    var coord = this.dataArrayCoords[0];
    this.playingHistory = true;
    
    var lat = coord[0];
    // //console.log(lat);
    var lng = coord[1];
    let outerThis = this
    var startPos = [lat, lng];
    this.speed = 200
    var iconselected = this.data.iconType;
    var delay = 100;
    
    
    var carIcon = {
      // path: car,
      url: '/assets/images/liveTrackIcons/rcar.png',
      scaledSize: new google.maps.Size(60, 60),
      //size: new google.maps.Size(30, 100),
      scale: .6,
      strokeColor: 'white',
      strokeWeight: .10,
      fillOpacity: 1,
      fillColor: 'blue',
      //fillColor: '#b75656',
      offset: '5%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };
    
    var bikeIcon = {
      // path: bike,
      url: '/assets/images/liveTrackIcons/rbike.png',
      scaledSize: new google.maps.Size(30, 50),
      //size: new google.maps.Size(30, 100),
      scale: .6,
      strokeColor: 'white',
      strokeWeight: .10,
      fillOpacity: 1,
      fillColor: 'blue',
      //fillColor: '#b75656',
      offset: '5%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };
    
    var truckIcon = {
      // path: truck,
      url: '/assets/images/liveTrackIcons/rtruck.png',
      scaledSize: new google.maps.Size(55, 85),
      //size: new google.maps.Size(30, 100),
      scale: .6,
      strokeColor: 'white',
      strokeWeight: .10,
      fillOpacity: 1,
      fillColor: 'blue',
      //fillColor: '#b75656',
      offset: '5%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };
    
    var userIcon = {
      // path: user,
      url: '/assets/images/liveTrackIcons/rcar.png',
      scaledSize: new google.maps.Size(30, 50),
      //size: new google.maps.Size(30, 100),
      scale: .6,
      strokeColor: 'white',
      strokeWeight: .10,
      fillOpacity: 1,
      fillColor: 'blue',
      //fillColor: '#b75656',
      offset: '5%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };
    
    var tractorIcon = {
      url: '/assets/images/liveTrackIcons/rtractor.png',
      scaledSize: new google.maps.Size(35, 50),
      //size: new google.maps.Size(30, 100),
      scale: .6,
      strokeColor: 'white',
      strokeWeight: .10,
      fillOpacity: 1,
      fillColor: 'blue',
      //fillColor: '#b75656',
      offset: '5%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };

    
    var busIcon = {
      // path: bus,
      url: '/assets/images/liveTrackIcons/rbus.png',
      scaledSize: new google.maps.Size(35, 50),
      //size: new google.maps.Size(30, 100),
      scale: .6,
      strokeColor: 'white',
      strokeWeight: .10,
      fillOpacity: 1,
      fillColor: 'blue',
      //fillColor: '#b75656',
      offset: '5%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(25, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    }
    
    
    var icons = {
      "car": carIcon,
      "bike": bikeIcon,
      "truck": truckIcon,
      "tractor": tractorIcon,
      "bus": busIcon,
      "user": userIcon
    }
    var that = this;

    var contentString
    
    map = this.gMap;
    
    var target = 0;
    // if(this.rangeDetector == true){
    //   target = this.indexValue; 
    // }
    // this.rangeDetector=false;
    var km_h = km_h || 50;
    
    
    if (!startPos.length)
    coords.push([startPos[0], startPos[1]]);
    
    that.goToPoint = function () {
      // //console.log("Go to point function");
      if(that.rangeDetector === true){
        a= that.indexValue;
        target   = that.indexValue;
        that.sliderValue = that.indexValue;
      }
      var lat = marker.position.lat();
      var lng = marker.position.lng();
      // that.getAddress(lat,lng);
      
      if(km_h === 0){
        km_h = 200 ;  
      }
      var step = (km_h * 1000 * delay) / 3600000; // in meters
      var dest = new google.maps.LatLng(
        coords[target][0], coords[target][1]);
      //  //console.log(coords[target][2])
      var r = coords[target][2];
      
      // outerThis.triptime = new Date(coords[target][4]);
      // console.log(outerThis.triptime);
      outerThis.speeed2 = r;
      outerThis.ext_voltage = '22v';
      
      outerThis.historyDate = coords[target][4];
      outerThis.ext_voltage = coords[target][5];
      // //console.log("outerThis.historyDate",coords);

      var distance = google.maps.geometry.spherical.computeDistanceBetween(dest, marker.position); // in meters
      
      var numStep = distance / step;
      
      var i = 0;
      var deltaLat = (coords[target][0] - lat) / numStep;
      var deltaLng = (coords[target][1] - lng) / numStep;
      // //console.log('cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',target);
      that.moveMarker = function () {
        // //console.log("Move Marker Function");
        // //console.log('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz',a,target);
        // ye wala movemarker function h  
        outerThis.sliderValue = a; 
        outerThis.cummulative_Distance  = coords[target][3] ; 
        lat += deltaLat;
        lng += deltaLng;
        i += step;
        // //console.log('icons[iconselected].rotation',icons[iconselected].rotation);
        let markerDOM: any;
        var status = "RUNNING";
        
        if (i < distance) {
          // let iconType = 'car';
          // //console.log('iconsiconsiconsiconsiconsicons',icons);
          // //console.log(icons['iconType'].url);
          // //console.log(icons[iconType]);
          // //console.log(icons[iconType].url);
          var msg;
          // //console.log('iconType',iconType);
          icons[iconType].url = that.iconSelector(status, iconType, msg);
          markerDOM = that.elementRef.nativeElement.querySelector("img[src='" + icons[iconType].url + "']");
          // //console.log('markerDOM',markerDOM);
          
          var head = google.maps.geometry.spherical.computeHeading(marker.getPosition(), new google.maps.LatLng(lat, lng));

          
          //console.log('head',head);
        
          // if (head != 0) {
            // icons[iconselected].rotation = head
           
            if (markerDOM) {
              markerDOM.style.transform = 'rotate(' + head + 'deg)';
            }
            // }
          marker.setIcon(icons[iconselected]);
          marker.setPosition(new google.maps.LatLng(lat, lng));

          map.setCenter({ lat: lat, lng: lng });
          // //console.log("Abinash");
          that.start = setTimeout(that.moveMarker, delay);
        }
        else {
          var head = google.maps.geometry.spherical.computeHeading(marker.getPosition(), dest);
         
          

          // var iconType = 'car';

          // //console.log(icons['iconType'].url);
          // //console.log(icons[iconType]);
          // //console.log(icons[iconType].url);
          
          icons[iconType].url = that.iconSelector(status, iconType, msg);
          markerDOM = that.elementRef.nativeElement.querySelector("img[src='" + icons[iconType].url + "']");
          
          if (markerDOM) {
              markerDOM.style.transform = 'rotate(' + head + 'deg)';
            }
          // }
          marker.setIcon(icons[iconselected]);
          marker.setPosition(dest);
          map.setCenter({ lat: coords[target][0], lng: coords[target][1] });
          // //console.log('target',target);
          target++;
          if (target == coords.length) { target = 0; }
          that.start = setTimeout(that.goToPoint, delay);
          
        }
      }
      a++
      
  
      that.rangeDetector = false;
      // //console.log("outside moveMarker function");
      if (a > coords.length) {
        // //console.log("Cord.length if condition");  
        outerThis.speeed2 = 0;
    
      }
      else {     
        // //console.log("Cord.length else condition");   
        that.moveMarker();
        km_h = outerThis.speed;
      }
    }
    var a = 0;
    
   
    // //console.log("Gotopoint function");
    that.goToPoint();
    
  }

  iconSelector(status, iconType, msg) {
    

    // var tempSpeed = msg.speed;
    // var tempIgn = msg.ignition;
    var iconUrl = "";
    // if(status !="OUT OF REACH"){
      //   if (((msg.speed != undefined) && (msg.speed != null)) && ((msg.ignition != null)&&(msg.ignition != undefined))) {
    //     if (parseInt(msg.ignition) == 0) {
      //       status = "STOPPED"
      //     }
    //     else if (msg.ignition == "1" && parseInt(msg.speed) > 0) {
      //       status = "RUNNING";
      //     } else {
        //       status = "IDLING"
    //     }
    //   }
    // }
    
    if (status == "OUT OF REACH") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/obike.png';
        return iconUrl;
      }
      if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/ocar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/obus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/otruck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/otractor.png';
        return iconUrl;
      }  else if (iconType == 'jcb') {
        iconUrl = '/assets/images/liveTrackIcons/ourjcb.png';
        return iconUrl;
      }
      else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_b.png';
        return iconUrl;
      }
      else {
        iconUrl = '/assets/images/liveTrackIcons/user_b.png';
        return iconUrl;
      }
      
    } else if (status == "STOPPED") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/sbike.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/scar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/sbus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/struck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/stractor.png';
        return iconUrl;
      }else if (iconType == 'jcb') {
        iconUrl = '/assets/images/liveTrackIcons/stoppedjcb.png';
        return iconUrl;
      }   else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_r.png';
        return iconUrl;
      }else {
        iconUrl = '/assets/images/liveTrackIcons/user_r.png';
        return iconUrl;
      }
    } else if (status == "RUNNING") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/rbike.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/rcar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/rbus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/rtruck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/rtractor.png';
        return iconUrl;
      } else if(iconType == 'jcb'){
        iconUrl = '/assets/images/liveTrackIcons/runningjcb.png';
        return iconUrl;
        
      }  else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_g.png';
        return iconUrl;
      } else {
        iconUrl = '/assets/images/liveTrackIcons/user_g.png';
        return iconUrl;
      }
    } else if (status == "IDLING") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/ibike.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/icar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/ibus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/itruck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/itractor.png';
        return iconUrl;
      }else if(iconType == "jcb" ){
        iconUrl = '/assets/images/liveTrackIcons/idlingjcb.png';
        return iconUrl;        

      } else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_y.png';
        return iconUrl;
      }  else {
        iconUrl = '/assets/images/liveTrackIcons/user_y.png';
        return iconUrl;
      }
    }else if (status == "NO DATA") {
      if (iconType == 'bike') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if(iconType == 'jcb'){
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else {
        iconUrl = '/assets/images/liveTrackIcons/user_g.png';
        return iconUrl;
      }
    }
  }

  
 
changeRange(){ 
  
  clearTimeout(this.start);
  this.rangeDetector = true;
  var rangeVal = document.getElementById("slider1");
 

  this.indexValue  = rangeVal['value'];

 if(this.tempMapHistory[0]['flag'] == 'stop'){
   this.marker4.setPosition({ lat: this.latLngLine[this.indexValue].lat, lng: this.latLngLine[this.indexValue].lng });
    this.gMap.setCenter({ lat: this.latLngLine[this.indexValue].lat, lng: this.latLngLine[this.indexValue].lng });
    this.goToPoint();
  
 } 
 if(this.tempMapHistory[0]['flag'] == 'start'){
  this.marker4.setPosition({ lat: this.latLngLine[this.indexValue].lat, lng: this.latLngLine[this.indexValue].lng });
  this.gMap.setCenter({ lat: this.latLngLine[this.indexValue].lat, lng: this.latLngLine[this.indexValue].lng });
  this.tempMapHistory[0]['flag'] = 'stop';
  this.goToPoint();

}

}
devicess:any;
plotGeofence(id){
 
  this.contactService.getperGeoFence(id).subscribe(      
    data => {
      this.devicess = data 
      // console.log(this.devicess);
      var cordin=[];
      let a = this.devicess[0].geofence.coordinates[0];
      for(let k=0;k<a.length;k++){
      let b ={
      lat : a[k][1],
      lng : a[k][0]
      }
   
      cordin.push(b);
    }  
      this.draw(cordin, this.devicess[0].geoname);
    });
}
plotGeofence2(id){
 
  this.contactService.getperGeoFence(id).subscribe(      
    data => {
      this.devicess = data 
      // console.log(this.devicess);
      var cordin=[];
      let a = this.devicess[0].geofence.coordinates[0];
      for(let k=0;k<a.length;k++){
        let b ={
      lat : a[k][1],
      lng : a[k][0]
      }
     
      cordin.push(b);
    }  
      this.draw(cordin, this.devicess[0].geoname);
    });
}

draw(zzz,yyy){
  
  var infoWindow;
 // console.log(typeof zzz)
  var GeoFencCoords = zzz
  var GeoName = yyy
  // plotPoly(GeoFencCoords,this.gMap);
  var that=this;
  // function plotPoly(GeoFencCoords,map) {  
    // console.log(map); 
    console.log('GeoFencCoords',GeoFencCoords);
    var bermudaTriangle = new google.maps.Polygon({
      paths: GeoFencCoords,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 3,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    
    bermudaTriangle.setMap(this.gMap);
    // Add a listener for the click event.
    bermudaTriangle.addListener('click', showArrays);
    infoWindow = new google.maps.InfoWindow;
  // }

  /** @this {google.maps.Polygon} */
  function showArrays(event) {
    // Since this polygon has only one path, we can call getPath() to return the
    // MVCArray of LatLngs.
    var vertices = this.getPath();

    var contentString = '<b>Geo Fence</b><br>' +
        'Name: ' + GeoName;
        
    infoWindow.setContent(contentString);
    infoWindow.setPosition(event.latLng);
    infoWindow.open(that.gMap);
  }
}

  
  
}

//   populateHistory: any;
//   routeId: any;
//    Load:boolean=false
//   constructor(private contactService: ContactService,private router: Router,private _flashMessagesService: FlashMessagesService,public dialogRef: MdDialogRef<TripHistoryComponent>,
//     @Inject(MD_DIALOG_DATA) public data: any) {

//     this.routeId = data.routeId;
//     // console.log(this.routeId);

//      }

//   ngOnInit() {
//     this.trip_history();
//   }


//   newArray=[]
//   trip_history(){
//      this.Load = true;
//     this.contactService.tripHistory(this.routeId)
//       .subscribe(res=>{
//         // console.log(res);
//         this.populateHistory = res;
//         this.Load = false;

//         // console.log('populatedhis',this.populateHistory);
//       },err=>{
//           this.Load = false;
//            this._flashMessagesService.show('Info : No Data Found', { cssClass: 'alert-danger', timeout: 2000 });
//       })
//   }


//   tab:any;
//   exportExcel()
// 	{   
  
// 	    var tab_text_1="<table border='2px'><tr bgcolor='#87AFC6'>";
// 	    var textRange; var j=0;
// 	    this.tab = document.getElementById('test_history'); // id of table

// 	    for(j = 0 ; j < this.tab.rows.length ; j++) 
// 	    {     
// 	        tab_text_1=tab_text_1+this.tab.rows[j].innerHTML+"</tr>";
// 	        //tab_text_1=tab_text_1+"</tr>";
// 	    }

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

// 	    return (sa);
// 	}
// }