import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../contact.service';
declare var google: any;
declare var swal: any;
import * as moment from 'moment-timezone';
declare var MarkerClusterer: any;
@Component({
  selector: 'app-live-history',
  templateUrl: './live-history.component.html',
  styleUrls: ['./live-history.component.scss']
})
export class LiveHistoryComponent implements OnInit {
  Fromdate = new Date();
  todate = new Date();
  deviceObj =[];
  Load: boolean;
  globalMap : any;
  globalMarker: any;
  emailid: any;
  useridd: any;
  latLngLine: any[];
  dev_id: any;
  ddid: any;
  latlongObjArr: any=[];
  path: any;
  speed: any;
  im: any;
  datee: string;
  time: any;
  dataArrayCoords: any=[];
  lat: any;
  lng: any;
  devicon: any;
  dis: boolean;
  stoppage_container: any[];
  arrival: Date;
  departure: Date;
  data2: any;
  total_dis: any;
  avg_speed: any;
  ideal_time: any;
  latLongArr2: any[];
  latitude: any;
  longitude: any;
  arrivalTime: string;
  departureTime: string;
  addresslocation: any;
  Durations: string;
  SpeedMeter2: boolean;
  speeed2: number=0;
  superAdmin: any;
  custtype: any;
  supadmin: any;
  dealerid: any;
  userID: any;
  constructor(private contactService:ContactService) { }

  ngOnInit() {
    var alpha = JSON.parse(window.atob(window.localStorage.token.split(".")[1]));
    console.log(alpha);
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    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.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    console.log(this.superAdmin);
    console.log(this.custtype);

    if(this.superAdmin == true){
      this.supadmin =this.useridd;
    }
     if(this.custtype == true){
      this.dealerid = this.useridd;
    }


    this.Fromdate.setHours(0,0,0);
    this.getAllDevice();
    var that = this;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {   
        var curr_position = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        }  
  
        var map = new google.maps.Map(document.getElementById('poiAddMap'),{
          center: {lat:  curr_position.lat, lng: curr_position.lng},
          zoom: 15
        });
        console.log(that.globalMap);
        that.globalMap = map;
        var icon1 = {
          url: "./assets/image/ico_direccion.png", // url
          scaledSize: new google.maps.Size(50, 50), // scaled size
        
      };
        var marker = new google.maps.Marker({
          position: curr_position,
          map: map,
          draggable:false,
          icon: icon1
        });

        that.globalMarker = marker;
      })
      }

  }


  getAllDevice() {
    this.Load = true;
    console.log(this.supadmin,this.dealerid,this.userID);
    var search ;
    this.contactService.alldevices1(this.useridd,this.emailid,this.supadmin,this.dealerid,search)
      .subscribe(res => {
        this.Load = false;   
        this.deviceObj = [];
        var Alldevices = {
          id: "all",
          viewValue: "ALL Devices",
          iconType : "",
          deviceId:""
        }
        console.log("device obj =>",res.devices);
        this.deviceObj.push(Alldevices);
        for (var i = 0; i < res.devices.length; i++) {
          Alldevices = {
            id: res.devices[i]._id,
            viewValue: res.devices[i].Device_Name ? res.devices[i].Device_Name : "",
            iconType : res.devices[i].iconType,
            deviceId : res.devices[i].Device_ID      
          }
          this.deviceObj.push(Alldevices)
        }
      }, err => {
        this.Load = false;
        console.log(err);
      })
  }

  deviceSelect: any = [];
  deviceName: any;
  filterDevices(dlr) {
    if(dlr.length == 0){
      this.deviceSelect =[];
    }
      if (dlr) {
          const filterdealerValue: any = dlr;
          this.deviceSelect = [];
          this.deviceSelect = this.deviceObj.filter(function(pp) {
              var t = pp.viewValue.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
              return t > -1;
          });
          return this.deviceSelect;
      }
  }

  inter(b) {
    // console.log(b);
    if (b == 'fast') {
      this.speed = 2 * this.speed;
      // console.log(this.speed)
    }
    else if (b == 'slow') {
      if (this.speed > 50) {
        this.speed = this.speed / 2;
        // console.log(this.speed)
      }
      else {
        /*  this.speed =200 */
      }
    }
    else {
      this.speed = 200
    }
    //this.play(null)
  }

  play(a) {
    var ongoingMoveMarker = null;
    this.SpeedMeter2 = true;
   
    // console.log("viewObj", this.dataArrayCoords)
    // console.log(this.dataArrayCoords);
    var map, marker;
  
    var coord = this.dataArrayCoords[0];
    // console.log(coord);
    var lat = coord[0];
    // console.log(lat);
    var lng = coord[1];
    let outerThis = this
    var startPos = [lat, lng];
    this.speed = 200


    var iconselected = this.devicon
    var delay = 100;
    var car = 'M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z';
    var bike = "M419 1754 l3 -44 -37 0 c-21 0 -34 4 -30 10 3 6 -1 10 -9 10 -19 0 -66 -21 -66 -30 0 -18 44 -44 71 -42 16 1 29 0 29 -2 0 -12 -24 -56 -30 -56 -4 0 -7 -6 -7 -12 0 -7 -8 -29 -16 -48 l-15 -35 -7 30 c-4 17 -8 36 -11 43 -6 19 -40 14 -69 -11 l-27 -23 16 -134 c12 -99 23 -149 41 -186 28 -57 25 -84 -10 -84 -34 0 -51 -25 -31 -45 9 -9 16 -33 16 -53 0 -30 -9 -46 -44 -84 -24 -27 -42 -48 -40 -48 2 0 -10 -21 -26 -47 -17 -27 -30 -61 -30 -79 0 -35 35 -189 52 -232 6 -15 10 -41 9 -59 -3 -34 19 -53 58 -53 12 0 21 -6 21 -14 0 -12 -7 -13 -32 -5 -44 12 -70 11 -66 -2 2 -6 21 -12 41 -14 21 -1 43 -7 49 -13 17 -17 23 -119 8 -137 -10 -12 -9 -19 3 -38 l15 -23 -46 23 c-29 15 -63 23 -94 23 -56 0 -61 -14 -17 -48 24 -20 42 -24 97 -24 63 -1 69 -3 109 -39 22 -21 38 -41 35 -44 -4 -4 -2 -5 3 -4 6 1 30 -3 55 -10 54 -16 142 -9 176 14 13 8 24 13 24 10 0 -3 16 13 36 34 35 39 36 40 103 39 59 -1 73 2 99 23 45 35 41 49 -17 49 -32 0 -64 -8 -97 -25 -27 -14 -42 -20 -33 -13 10 8 14 23 11 38 -10 54 -7 139 6 152 7 7 30 13 52 13 27 0 40 4 40 13 0 11 -9 13 -36 8 -19 -4 -42 -10 -50 -13 -10 -3 -12 0 -8 10 3 8 18 17 33 20 23 5 30 13 35 41 4 18 13 47 20 62 8 16 26 77 41 136 l26 106 -45 90 c-24 49 -56 102 -70 119 -14 17 -23 33 -19 37 3 3 1 6 -5 6 -15 0 -16 57 -1 62 22 7 -3 38 -31 38 -19 0 -31 6 -34 18 -7 20 38 114 49 104 5 -4 5 -2 2 4 -4 7 0 67 9 135 8 68 13 134 10 145 -8 29 -60 51 -81 34 -8 -7 -15 -22 -15 -35 0 -43 -13 -33 -46 36 -19 39 -34 73 -34 76 0 3 13 3 30 1 22 -3 35 2 50 17 27 29 17 49 -26 53 -22 1 -33 -2 -29 -8 4 -6 -8 -10 -29 -10 -34 0 -35 1 -38 43 -3 42 -3 42 -43 43 l-40 1 4 -43z m-140 -187 c13 -16 5 -27 -21 -27 -14 0 -18 -5 -14 -17 8 -29 26 -196 24 -220 -5 -48 -19 -2 -32 106 -16 127 -15 133 3 155 16 20 25 20 40 3z m402 -3 c7 -9 14 -22 15 -30 4 -26 -25 -237 -34 -246 -12 -12 -12 12 0 127 6 55 16 103 22 107 6 4 -2 12 -22 19 -26 9 -30 14 -21 25 15 18 24 18 40 -2z m-123 -226 c48 -23 54 -30 46 -51 -5 -13 -10 -14 -39 -1 -50 21 -163 18 -207 -5 -35 -17 -37 -17 -41 0 -7 24 23 49 85 70 58 20 89 18 156 -13z m28 -469 c39 -36 56 -76 56 -134 2 -169 -205 -230 -284 -85 -26 47 -21 155 7 176 10 8 15 14 10 14 -13 0 27 41 50 51 11 5 46 7 77 6 45 -3 64 -9 84 -28z m131 -37 c7 -8 10 -19 7 -23 -3 -5 -1 -9 4 -9 17 0 21 -41 10 -103 -10 -59 -28 -100 -28 -64 0 14 -44 137 -75 209 -6 15 -2 16 32 11 21 -3 43 -12 50 -21z m-455 -49 c-15 -38 -30 -71 -35 -74 -5 -3 -8 -9 -8 -13 3 -21 0 -36 -8 -36 -5 0 -11 30 -13 68 -5 61 -3 69 20 95 14 15 36 27 48 27 l22 0 -26 -67z m377 -317 c19 14 25 14 32 3 13 -21 12 -23 -21 -42 -16 -10 -30 -23 -30 -28 0 -6 -4 -8 -8 -5 -4 2 -9 -9 -10 -25 -2 -22 2 -29 16 -29 14 0 21 -12 29 -44 10 -43 9 -45 -13 -43 -13 1 -29 10 -37 21 -13 17 -15 14 -37 -40 -13 -33 -30 -65 -38 -72 -9 -6 -12 -12 -7 -12 4 0 0 -9 -10 -20 -35 -39 -107 -11 -117 45 -1 11 -9 26 -15 33 -12 12 -17 33 -15 54 1 3 -5 11 -13 18 -11 9 -16 7 -25 -9 -12 -23 -50 -29 -50 -7 0 44 14 76 32 76 17 0 19 4 13 23 -4 12 -7 30 -8 39 -1 9 -4 15 -8 12 -4 -2 -19 6 -33 18 -19 16 -23 27 -17 37 8 12 13 12 34 -2 l25 -16 7 39 c4 22 8 40 9 40 1 0 18 -9 39 -19 l37 -19 -28 -8 c-15 -4 -30 -7 -33 -6 -3 0 -6 -11 -5 -26 l1 -27 125 0 c120 0 125 1 128 21 2 16 -5 25 -27 34 l-31 12 33 22 32 22 10 -43 c10 -43 10 -44 34 -27z m-161 11 c2 -10 -3 -17 -12 -17 -18 0 -29 16 -21 31 9 14 29 6 33 -14z m-58 -11 c0 -16 -18 -31 -27 -22 -8 8 5 36 17 36 5 0 10 -6 10 -14z m108 -10 c3 -12 -1 -17 -10 -14 -7 3 -15 13 -16 22 -3 12 1 17 10 14 7 -3 15 -13 16 -22z m-148 -5 c0 -14 -18 -23 -31 -15 -8 4 -7 9 2 15 18 11 29 11 29 0z m198 -3 c-3 -7 -11 -13 -18 -13 -7 0 -15 6 -17 13 -3 7 4 12 17 12 13 0 20 -5 18 -12z m-430 -224 c37 -10 25 -23 -14 -14 -19 5 -38 11 -41 14 -8 8 26 7 55 0z m672 -3 c-8 -5 -35 -11 -60 -15 l-45 -6 35 14 c39 16 96 21 70 7z m-454 -113 l29 -30 -30 15 c-17 8 -38 24 -48 35 -18 20 -18 20 1 15 11 -2 33 -18 48 -35z m239 15 c-11 -8 -33 -21 -50 -30 l-30 -15 30 31 c16 17 35 29 42 27 7 -3 13 0 13 6 0 6 3 8 7 4 5 -4 -1 -14 -12 -23z"
    var truck = 'M180 1725 c0 -8 -21 -25 -47 -37 -27 -12 -58 -31 -70 -42 l-23 -20 0 -495 0 -496 23 -18 c12 -10 31 -24 42 -32 20 -13 20 -14 -2 -37 -21 -22 -23 -34 -23 -131 0 -65 -4 -107 -10 -107 -5 0 -10 -7 -10 -15 0 -8 5 -15 10 -15 6 0 10 -31 10 -74 0 -44 5 -78 11 -82 8 -4 7 -9 -2 -15 -38 -23 96 -89 181 -89 85 0 219 66 181 89 -9 6 -10 11 -2 15 6 4 11 38 11 82 0 43 4 74 10 74 6 0 10 7 10 15 0 8 -4 15 -10 15 -6 0 -10 43 -10 108 0 96 -2 108 -20 120 -30 18 -24 38 20 69 l40 28 0 491 0 491 -22 24 c-22 24 -86 59 -106 59 -5 0 -12 9 -15 20 -5 18 -14 20 -91 20 -70 0 -86 -3 -86 -15z m115 -101 c21 -8 35 -45 28 -72 -7 -29 -47 -44 -78 -30 -29 13 -38 36 -29 72 7 30 43 44 79 30z m-148 -726 c-1 -134 -2 -25 -2 242 0 267 1 376 2 243 2 -134 2 -352 0 -485z m250 0 c-1 -134 -2 -25 -2 242 0 267 1 376 2 243 2 -134 2 -352 0 -485z m-102 326 c21 -9 35 -46 28 -74 -12 -44 -93 -46 -108 -1 -17 54 27 95 80 75z m20 -436 c2 -2 6 -15 10 -30 10 -38 -26 -72 -68 -64 -37 8 -35 6 -43 43 -8 42 18 67 64 59 19 -3 36 -6 37 -8z m18 -245 c-36 -16 -102 -16 -130 0 -18 10 -7 12 68 12 80 0 87 -1 62 -12z m-203 -69 c0 -21 -4 -33 -10 -29 -5 3 -10 19 -10 36 0 16 5 29 10 29 6 0 10 -16 10 -36z m300 1 c0 -24 -5 -35 -15 -35 -15 0 -22 50 -8 63 15 15 23 5 23 -28z m-300 -87 c0 -24 -5 -50 -10 -58 -7 -11 -10 2 -10 43 0 31 4 57 10 57 6 0 10 -19 10 -42z m300 -20 c0 -43 -3 -58 -10 -48 -13 20 -23 87 -15 100 15 25 25 5 25 -52z m-201 -44 c31 -4 80 -2 108 4 59 10 70 5 75 -43 3 -29 2 -30 -57 -38 -58 -8 -199 -2 -229 9 -12 5 -12 11 2 45 11 28 20 38 30 34 9 -3 40 -8 71 -11z m147 -222 c-14 -15 -15 -13 -3 17 8 23 13 28 15 16 2 -10 -3 -25 -12 -33z m-213 18 c3 -11 1 -20 -4 -20 -5 0 -9 9 -9 20 0 11 2 20 4 20 2 0 6 -9 9 -20z m267 -25 c0 -2 -10 -10 -22 -16 -21 -11 -22 -11 -9 4 13 16 31 23 31 12z'
    var user = "M256,0C156.011,0,74.667,81.344,74.667,181.333c0,175.296,167.232,321.92,174.357,328.064 c2.005,1.728,4.48,2.603,6.976,2.603c2.496,0,4.971-0.875,6.976-2.603c7.125-6.144,174.357-152.768,174.357-328.064 C437.333,81.344,355.989,0,256,0z M256,486.869C224.363,457.067,96,327.125,96,181.333c0-88.235,71.765-160,160-160 s160,71.765,160,160C416,327.125,287.637,457.067,256,486.869z M344.725,238.144c-5.461-3.328-10.475-5.419-15.509-6.571l-31.957-8.021l-1.323-5.376 c8.32-9.088,14.187-20.821,16.597-33.088c5.696-2.923,9.877-8.491,10.795-15.211l2.347-18.688 c0.64-5.525-1.067-11.093-4.672-15.296c-1.173-1.387-2.56-2.603-4.075-3.605l0.512-11.2l2.069-2.048 c5.803-6.293,11.051-17.003,3.563-31.509c-0.661-1.643-1.301-2.923-2.453-4.821c-5.547-8.533-17.045-18.731-40.299-18.731 c-3.84,0-9.131,0.235-15.189,1.216c-7.893,1.323-15.168,4.011-21.632,8.043c-43.968,1.6-49.152,25.323-49.152,43.221 c0,3.456,0.619,10.005,1.195,15.467c-1.579,0.981-3.029,2.219-4.288,3.605c-3.797,4.245-5.589,9.963-4.928,15.765l2.368,18.688 c0.939,6.891,5.397,12.587,11.925,15.424c2.368,11.691,7.915,22.955,15.68,31.915l-1.536,6.208l-31.723,7.979 c-5.291,1.195-10.304,3.307-15.765,6.613c-2.624,1.579-4.437,4.224-4.971,7.232s0.235,6.101,2.133,8.512 c22.507,28.459,55.893,44.8,91.563,44.8s69.056-16.341,91.563-44.779c1.899-2.411,2.667-5.483,2.133-8.512 C349.163,242.368,347.349,239.723,344.725,238.144z M256,277.333c-24.256,0-47.232-9.28-64.896-25.856l35.115-8.789 c3.819-0.981,6.805-3.947,7.744-7.787l4.48-18.133c0.939-3.733-0.235-7.701-3.051-10.325c-8.277-7.765-13.717-19.2-14.592-30.592 c-0.427-5.547-5.376-8.619-10.944-8.619l-2.688-17.024c3.072,0,5.973-1.323,8-3.605c2.027-2.304,2.965-5.333,2.581-8.384 c0,0-2.048-16.299-2.048-21.739c0-11.115,0-21.611,31.275-21.973c2.155-0.021,4.267-0.704,6.037-1.963 c4.501-3.2,9.771-5.312,15.573-6.272c4.651-0.747,8.768-0.939,11.755-0.939c10.965,0,18.517,3.051,22.4,9.024l8.939-5.803 l-8,7.851c2.752,5.355,1.429,6.763,0.448,7.851l-4.693,4.693c-1.877,1.877-2.987,4.395-3.115,7.04l-1.067,23.04 c-0.128,2.859,0.384,4.843,2.304,6.955c1.941,2.091,4.117,2.56,6.955,2.667l-1.579,17.344c-5.589,0-10.219,4.309-10.645,9.877 c-0.875,11.627-6.699,23.467-15.189,30.976c-2.965,2.624-4.245,6.677-3.307,10.539l4.267,17.472 c0.939,3.819,3.925,6.827,7.765,7.808l35.072,8.811C303.232,268.053,280.256,277.333,256,277.333z"

    var carIcon = {
      path: car,
      scale: .6,
      strokeColor: 'white',
      strokeWeight: .10,
      fillOpacity: 1,
      fillColor: 'green',
      //fillColor: '#b75656',
      offset: '5%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(10, 25), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };

    var bikeIcon = {
      path: bike,

      scale: .019,
      strokeColor: 'black',
      strokeWeight: .90,
      fillOpacity: 0.8,
      fillColor: 'green',
      //fillColor: '#b75656',
      offset: '0%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(400, 900), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };

    var truckIcon = {
      path: truck,

      scale: .03,
      strokeColor: 'black',
      strokeWeight: .90,
      fillOpacity: 0.8,
      fillColor: 'green',
      //fillColor: '#b75656',
      offset: '0%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(250, 700), // orig 10,50 back of car, 10,0 front of car, 10,25 center of car,
      rotation: 0
    };


    var userIcon = {
      path: user,

      scale: .08,
      strokeColor: 'black',
      strokeWeight: 1.2,
      fillOpacity: 1,
      fillColor: 'green',
      //fillColor: '#b75656',
      offset: '0%',
      // rotation: parseInt(heading[i]),
      anchor: new google.maps.Point(250, 700), // 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,
      "user" : userIcon
    }

    // If you set the delay below 1000ms and you go to another tab,
    // the setTimeout function will wait to be the active tab again
    // before running the code.
    // See documentation :
    // https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#Inactive_tabs
    var contentString

    function animateMarker(marker, coords, km_h, iconType) {

      // console.log("speed variable", km_h);

      //console.log(km_h);
      //     console.log($scope.trackerType)
      var target = 0;
      var km_h = km_h || 50;
      if (!startPos.length)
        coords.push([startPos[0], startPos[1]]);



      function goToPoint() {
        var lat = marker.position.lat();
        var lng = marker.position.lng();
        var step = (km_h * 1000 * delay) / 3600000; // in meters
        // let outerThis
        var dest = new google.maps.LatLng(
          coords[target][0], coords[target][1]);
        //  console.log(coords[target][2])
        var r = coords[target][2]
        outerThis.speeed2 = r

        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;

        function moveMarker() {


          lat += deltaLat;
          lng += deltaLng;
          i += step;

          if (i < distance) {

            var head = google.maps.geometry.spherical.computeHeading(marker.getPosition(), new google.maps.LatLng(lat, lng))
            if (head != 0) {
              icons[iconselected].rotation = head
            }
            marker.setIcon(icons[iconselected]);
            marker.setPosition(new google.maps.LatLng(lat, lng));

            map.setCenter({ lat: lat, lng: lng });
            setTimeout(moveMarker, delay);
          }
          else {
            var head = google.maps.geometry.spherical.computeHeading(marker.getPosition(), dest)
            if (head != 0) {
              icons[iconselected].rotation = head
            }
            marker.setIcon(icons[iconselected]);
            marker.setPosition(dest);
            map.setCenter({ lat: coords[target][0], lng: coords[target][1] });
            target++;
            if (target == coords.length) { target = 0; }

            setTimeout(goToPoint, delay);
          }
        }
        a++
        if (a > coords.length) {
        outerThis.speeed2 = 0
        }
        else {
          moveMarker();
          km_h = outerThis.speed
        }
      }
      var a = 0;
        goToPoint();
    }


    function initialize() {
      var myOptions = {
        zoom: 16,
        center: new google.maps.LatLng(lat, lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
       map = new google.maps.Map(document.getElementById("poiAddMap"), myOptions);
      // console.log("Abinash");
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(startPos[0], startPos[1]),
        map: map,

      });

      google.maps.event.addListenerOnce(map, 'idle', function () {

        animateMarker(marker, outerThis.dataArrayCoords, outerThis.speed, iconselected);
      });
      // console.log("Abinash")

      var flightPath = new google.maps.Polyline({
        path: outerThis.latLngLine,
        geodesic: true,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2,
        icons: [{
          icon: {
            strokeColor: '#800000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            path: google.maps.SymbolPath.FORWARD_OPEN_ARROW
          },
          offset: '0',
          repeat: '100px'
        }],

      });

      flightPath.setMap(map);

    }

    initialize();

  }

  generateHistory(){
    console.log(this.Fromdate);
    console.log(this.todate);
    console.log(this.deviceSelect);
    let isMapInit = false;
    this.latLngLine = [];
      var position;
      let outerThis = this ;
      this.dev_id = this.deviceSelect[0];
      //  console.log(this.date1)
      var fromtime = new Date(this.Fromdate).toISOString();
      var totime = new Date(this.todate).toISOString();
      console.log("deviceID=>",this.dev_id);                 
      if (fromtime > totime) {
        this.Load = false;
        let message = "Error: From Time Never Greater then To Time";
        swal(
          'Date',
          'From Time Never Greater then To Time',
          'error'
        )
      
        // show swal error here 
      }
     
      else if (this.dev_id === null || this.dev_id === undefined || this.dev_id === '') {
        this.Load = false;
        let message = "Error: Please choose a device";
        swal(
          'Select device',
          'Please choose a device',
          'error'
        )
   
        // show swal error here 
      }
      else {
        this.ddid = this.dev_id.deviceId;
        this.devicon = this.dev_id.iconType;
        this.Load = true;
        this.contactService.getCurrentLocation(this.ddid, fromtime, totime).subscribe((data3) => {
          this.Load =false;
          this.latlongObjArr = data3;
          console.log("LatlongObjectArray=>",this.latlongObjArr)
          initialize();
          let cluster_arr = [];
          this.path = flightPath.getPath(); 
          for (let i = this.latlongObjArr.length - 1; i > 0; i--) {   
         
            var d_name = this.dev_id.viewValue;
            this.speed = this.latlongObjArr[i].speed + "Km/hr";
            this.im = this.latlongObjArr[i].imei;
            // this.datee = JSON.stringify(this.latlongObjArr[i].insertionTime).split('"')[1].split('T')[0];
            // var gmtDateTime = moment.utc(JSON.stringify(this.latlongObjArr[i].insertionTime).split('T')[1].split('.')[0], "HH:mm:ss");
            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'); 
              // console.log("Insertion date=>",insTime);
              // console.log(this.datee);
  
            var content = '<div id="content"><div id="bodyContent"><div><br><b>DEVICE NAME : ' + d_name + '</b><br><b>IMEI : ' + this.im + '</b><br><b>DEVICE DATE : ' + this.datee + '</b><br><b>SPEED : ' + this.speed + '</b></div>'
            '</div></div>'
  
         
            var arr = [];
            arr.push(this.latlongObjArr[i].lat);
            arr.push(this.latlongObjArr[i].lng);
            arr.push(this.latlongObjArr[i].speed);
            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';
              var markerCurrent:any;
              var markerSrc:any
// =============================================added==========================================
              // this.lat = this.latlongObjArr[i].lat;
              // this.lng = this.latlongObjArr[i].lng;

              // ====================================added==============================================
             
        
              // this.path.push(new google.maps.LatLng(this.lat, this.lng));

            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));
  
              var markersPast = new google.maps.Marker({
                position: new google.maps.LatLng(this.lat, this.lng),
              
                icon: { path: google.maps.SymbolPath.CIRCLE, fillColor: '#00F', fillOpacity: 0.6, strokeColor: '#00A', strokeOpacity: 0.9, strokeWeight: 1, scale: 2 },
  
              })
  
              markersPast['infowindow'] = new google.maps.InfoWindow({ content: content }); google.maps.event.addListener(markersPast, 'click', function () { this['infowindow'].open(this.globalMap, this); });
  
              cluster_arr.push(markersPast);
  
  
              if (i == 1) {
                markerCurrent = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: this.globalMap,
                  icon :iconDest
  
                });
                this.globalMap.setCenter(new google.maps.LatLng(this.lat, this.lng))
                flightPath.setMap(this.globalMap);
              }
  
              if(i ==( this.latlongObjArr.length - 1)){
                markerSrc = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: this.globalMap,
                  icon: iconSrc
  
                });
              }
           
            }
            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));
                var markersPast = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  //map: map,
                  icon: { path: google.maps.SymbolPath.CIRCLE, fillColor: '#00F', fillOpacity: 0.6, strokeColor: '#00A', strokeOpacity: 0.9, strokeWeight: 1, scale: 2 },
  
                })
                markersPast['infowindow'] = new google.maps.InfoWindow({ content: content }); google.maps.event.addListener(markersPast, 'click', function () { this['infowindow'].open(this.globalMap, this); });
               
                cluster_arr.push(markersPast);
  
              }
              
              console.log("this.path=>",this.path);
  
              if (i == 1) {
                console.log(this.lat,this.lng);
                markerCurrent = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: this.globalMap,
                  icon : iconDest
  
                });
                this.globalMap.setCenter(new google.maps.LatLng(this.lat, this.lng))
                flightPath.setMap(this.globalMap);
              }
  
              if(i == ( this.latlongObjArr.length - 1)){
                console.log(this.lat,this.lng);
                markerSrc = new google.maps.Marker({
                  position: new google.maps.LatLng(this.lat, this.lng),
                  map: this.globalMap,
                  icon : iconSrc
  
                });
              } 
            }
          }
          // console.log(this.dataArrayCoords);
          var markerCluster = new MarkerClusterer(this.globalMap, cluster_arr, { zoomOnClick: true, minimumClusterSize: 50, gridSize: 50, maxZoom: 15, imagePath: '/assets/images/m' });
          /*             this.spinnerService.hide();
          */
          //  this.Playback(this.latlongObjArr)
  
         this.dis = true
  
  
        });
  
        //stoppage function
  
        var stop_locations = [];
        this.contactService.stoppage_points(this.dev_id.id, fromtime, totime, this.useridd)
          .subscribe((res) => {
  
            console.log("stopage Point => ", res);
            // console.log(res);
            let test = res;
            // console.log("parking Point=>",test);
            if(test.length == 0 ){
              // error of no stoppagepoint found
             //this._flashMessagesService.show('No stoppage found !!!', { cssClass: 'alert-success', timeout: 2000 });
            }
            // console.log(test.length);
            //   this.stoppage_container = [];
            for (var i = 0; i < test.length; i++) {
  
              this.stoppage_container = [];
              this.stoppage_container.push(test[i].lat);
              this.stoppage_container.push(test[i].long);
              // console.log(test[i].lat);
              // console.log(test[i].long);
  
              //  this.stoppage_container.push(test[i].lat);
              //   this.stoppage_container.push(test[i].long);
              this.arrival = new Date(test[i].arrival_time);
              this.stoppage_container.push(this.arrival);
              // console.log(this.arrival);
              this.departure = new Date(test[i].departure_time);
              this.stoppage_container.push(this.departure);
              // console.log(this.departure)
  
              stop_locations.push(this.stoppage_container)
  
  
            }
             console.log("stopLocationPush ======>",stop_locations);
           
             console.log("Stoppage location sflksajfslfksdnfslk");
            // service for display averagespeed and total distance on map as a infowindow
            // console.log("fromTime", fromtime);
            // console.log("totime", totime);
            console.log("entering getDistance method");
            this.contactService.getDistance(this.ddid, fromtime, totime,undefined).subscribe((data3) => {
               console.log("response for totaldistance");
              this.data2 = data3;
              console.log("getdistanceService",this.data2)
              // initialize();
              //  console.log(this.data2);
              let a = this.data2["Distance"]?this.data2["Distance"]:0;
                console.log(a);
              this.total_dis = a;
              let b = this.data2["Average Speed"]?this.data2["Average Speed"]:0;
              this.avg_speed = b;
              this.ideal_time = this.data2["Idle Time"]?this.data2["Idle Time"]:0;
              customTxt = "<html> <head><style> </style> </head><body>Total Distance - " + this.total_dis + " Km<br>Average Speed - " + this.avg_speed + " Km/hr <br>Ideal Time - " + this.ideal_time + " min</body> </html> "
        
              console.log("customtext = >",customTxt);
              var centerControlDiv = document.createElement('div');
              var centerControl = new CenterControl(centerControlDiv, this.globalMap, customTxt);
               this.globalMap.controls[google.maps.ControlPosition.LEFT_TOP].push(centerControlDiv);
              //  console.log("displaydiv=>",centerControlDiv);
              if(stop_locations.length > 0){
                initParking();
               }else{
                 console.log("Inside no stoppage function");
                // swal(
                //   'No stoppage',
                //   'No stoppage detail found',
                //   'error'
                // )
               }
            })
          })
  
        // console.log(this.dev_id.id);
      }
      // console.log(totime)
      this.latLongArr2 = [];
      var customTxt;
      var txt;

      function CenterControl(controlDiv, map, text) {
  
        // Set CSS for the control border.
        var controlUI = document.createElement('div');
        controlUI.style.backgroundColor = '#fff';
        controlUI.style.border = '2px solid #fff';
        controlUI.style.borderRadius = '3px';
        controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
        controlUI.style.cursor = 'pointer';
        controlUI.style.marginBottom = '22px';
        controlUI.style.textAlign = 'left';
        controlUI.style.marginLeft = '11px';
        controlUI.style.opacity = "0.9";
        controlDiv.appendChild(controlUI);
  
        // Set CSS for the control interior.
        var controlText = document.createElement('div');
        controlText.style.color = 'rgb(25,25,25)';
        controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
        controlText.style.fontSize = '16px';
        controlText.style.lineHeight = '38px';
        controlText.style.paddingLeft = '5px';
        controlText.style.paddingRight = '5px';
        controlText.innerHTML = text;
        controlUI.appendChild(controlText);
  
        // Setup the click event listeners: simply set the map to Chicago.
  
  
      }
  
      function geocodePosition(pos, callback) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          latLng: pos
        }, function (responses) {
          callback(responses[0].formatted_address)
  
        });
      }
      var k;
  
      function initParking(){
        //  console.log(outerThis.stop_locations);
        // if(!isMapInit){
        const myOptions = {
          zoom: 15,
          center: new google.maps.LatLng(18.602941, 73.777147),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // console.log(myOptions);
        // map = new google.maps.Map(document.getElementById('map2'), myOptions);
        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(outerThis.globalMap);
        // console.log("Map Intialized")
        isMapInit = true;
  
        // ============================
        var pinImage = new google.maps.MarkerImage("https://png.icons8.com/office/30/000000/parking.png");
        var infowindow = new google.maps.InfoWindow();
  
        var marker: any, k: any;
        var l: number
         console.log('stoppagelocationArr',stop_locations);
       
          for (l = 0; l < stop_locations.length; l++) {
            outerThis.latitude = stop_locations[l][0];
            outerThis.longitude = stop_locations[l][1];
            outerThis.arrivalTime = new Date(stop_locations[l][2]).toLocaleString();
    
            outerThis.departureTime = new Date(stop_locations[l][3]).toLocaleString();
            outerThis.addresslocation = stop_locations[l][4];
            
            var fd = new Date(outerThis.arrivalTime).getTime();
            var td = new Date(outerThis.departureTime).getTime();
            var time_difference = td - fd;
            var total_min = time_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 + ':' + rminutes
      
            marker = new google.maps.Marker({
              position: new google.maps.LatLng(stop_locations[l][0], stop_locations[l][1]),
              map: outerThis.globalMap,
              icon: pinImage,
    
            });
    
            google.maps.event.addListener(marker, 'dragend', function () {
    
              this.geocodePosition(marker.getPosition());
            });
            outerThis.globalMap.setCenter(marker.getPosition());
    
    
            var content = '<div ><div> Arrival Time-: '
              + outerThis.arrivalTime + '</div><br><div>Departure Time-: '
              + outerThis.departureTime + '</div><br><div>Time Duration-: '
              + outerThis.Durations + ' </div></br><div> Latitude-: '
              + outerThis.latitude + ' </div></br><div> Longitude-: '
              + outerThis.longitude + ' </div><div>'
    
    
            // console.log("show content=>", content);
            google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
              return function () {
                geocodePosition(marker.getPosition(), function (result) {
                  infowindow.setContent(content);
                  infowindow.open(outerThis.globalMap, marker, content);
                });
              }
            })(marker, content, infowindow));     
          }

           console.log("Inside no stoppage function");

      }
  
      function initialize() {
  
        //  console.log(outerThis.stop_locations);
        // if(!isMapInit){
        const myOptions = {
          zoom: 15,
          center: new google.maps.LatLng(18.602941, 73.777147),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        // console.log(myOptions);
        outerThis.globalMap = new google.maps.Map(document.getElementById('poiAddMap'), myOptions);
        var trafficLayer = new google.maps.TrafficLayer();
        trafficLayer.setMap(outerThis.globalMap);
        // console.log("Map Intialized")
        isMapInit = true;
  
        // ============================
        var pinImage = new google.maps.MarkerImage("https://png.icons8.com/office/30/000000/parking.png");
        var infowindow = new google.maps.InfoWindow();
  
        var marker: any, k: any;
        var l: number
         console.log('stoppagelocationArr',stop_locations);
        for (l = 0; l < stop_locations.length; l++) {
          outerThis.latitude = stop_locations[l][0];
          outerThis.longitude = stop_locations[l][1];
          outerThis.arrivalTime = new Date(stop_locations[l][2]).toLocaleString();
  
          outerThis.departureTime = new Date(stop_locations[l][3]).toLocaleString();
          outerThis.addresslocation = stop_locations[l][4];
          
          var fd = new Date(outerThis.arrivalTime).getTime();
          var td = new Date(outerThis.departureTime).getTime();
          var time_difference = td - fd;
          var total_min = time_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 + ':' + rminutes
         
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(stop_locations[l][0], stop_locations[l][1]),
            map: outerThis.globalMap,
            icon: pinImage,
  
          });
  
          google.maps.event.addListener(marker, 'dragend', function () {
  
            this.geocodePosition(marker.getPosition());
          });
          outerThis.globalMap.setCenter(marker.getPosition());
  
  
          var content = '<div ><div> Arrival Time-: '
            + outerThis.arrivalTime + '</div><br><div>Departure Time-: '
            + outerThis.departureTime + '</div><br><div>Time Duration-: '
            + outerThis.Durations + ' </div></br><div> Latitude-: '
            + outerThis.latitude + ' </div></br><div> Longitude-: '
            + outerThis.longitude + ' </div><div>'
  
  
          // console.log("show content=>", content);
          google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) {
            return function () {
              geocodePosition(marker.getPosition(), function (result) {
                infowindow.setContent(content);
                infowindow.open(this.globalMap, marker, content);
              });
            }
          })(marker, content, infowindow));     
        } 
      }
  
      var lineSymbol = {
        path: 'M 0,-1 0,1',
        strokeOpacity: 1,
        scale: 4
      };
  
      var flightPath = new google.maps.Polyline({
        geodesic: true,
        strokeColor: '#0000FF',
        strokeOpacity: 1.0,
        strokeWeight: 2,
        icons: [{
          icon: {
            strokeColor: '#800000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            path: google.maps.SymbolPath.FORWARD_OPEN_ARROW
          },
          offset: '0',
          repeat: '100px'
        }],
  
      });
  }


}











// this.globalMap =  new google.maps.Map(document.getElementById('poiAddMap'),{
//   center: {lat:  25.594095, lng: 85.137566},
//   zoom: 15
// });
// var icon1 = {
//   url: "./assets/image/ico_direccion.png", // url
//   scaledSize: new google.maps.Size(50, 50), // scaled size

//   };
// this.globalMarker = new google.maps.Marker({
//   position: {lat:  25.594095, lng: 85.137566},
//   map: this.globalMap,
//   draggable:false,
//   icon: icon1
// });
