import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
import { Router } from '@angular/router';
import { MdDialog } from '@angular/material';
import { PoiListComponent } from '../poi-list/poi-list.component';


declare var google: any;

@Component({
  selector: 'app-point-of-intrest',
  templateUrl: './point-of-intrest.component.html',
  styleUrls: ['./point-of-intrest.component.scss']
})
export class PointOfIntrestComponent implements OnInit {
  POIPayload: any;
  PoI_id: any;
  grpName: any;
  before: any;
  logoutbut: boolean;
  cust: boolean = false;
  logo: any;
  text: any;
  fs: any; ls: any; emailid: any; or: any; useridd: any; mb: any; custtype: any; dealer: any;
  showImage: any;
  groups = [];
  group_info: any;
  myInput: any;
  deviceId: any;
  device_update: any;
  superAdmin: Boolean = false;
  route_detail_show = [];
  route: any;
  route_1: any;
  Fromdate: any;
  todate: any;
  routeRadius: any;
  driverName: any;
  Load: any;
  data_descip: any;
  showMeter:boolean=true;
  POI_marker = [];
  marker_poi: any;
  test: any;
  pathObj: any;
  divehistory: any;
  errormsg: any;
  current_add: any;
  globalComponentMap: any;
  mapOptions: any;
  latlongObjArr: any;
  latLngLine: any = [];
  coordreplaydata: any = [];
  _goToPoint:any;
  _moveMarker:any;
  delay: any=100;
  start: any;
  flag: any='init';

   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';
   carIcon = {
    path: this.car ,
    scale: .6,
    strokeColor: 'white',
    strokeWeight: .10,
    fillOpacity: 1,
    fillColor: 'blue',
    //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
  };

       icons = {
    "car": this.carIcon
  }
  speedmeterVal: any;
  newMarker: any;
  activateNewMarker: any;
  insertionTime: any;

  constructor(private router: Router, private contactService: ContactService, public dialog: MdDialog) { }

  ngOnInit() {

    this.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];
    window.localStorage['DataUpdate'] = 'Tthis.rue'

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

    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.divehistory = JSON.parse(localStorage.getItem('poiData'));
    // console.log("deviceHistory=>",this.divehistory);
    this.getDeviceHistory();

    this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    // console.log('testing', this.useridd);
    if (this.custtype == true) {
      this.cust = true;
    }
  
    if (this.mb.charAt(0) == "n") {
      this.mb = ' '
    }
    if (window.localStorage['Custumer'] == 'ON') {
      this.logoutbut = false
      this.dealer = true
    }
    else {
      this.logoutbut = true;
    }

    this.current_add = new google.maps.LatLng(18.633995, 73.808454);

    this.mapOptions = {
      zoom: 16,
      center: this.current_add
    };

    this.globalComponentMap = new google.maps.Map(document.getElementById('showMap'), this.mapOptions);
    // alert(this.POIPayload);
    // this.routeDetails(this.useridd);
    // console.log(this.POIPayload.payload.poi.length);
    //this.showRoute(this.POIPayload);
    this.getPOI();

    // console.log(this.POI_marker);
  }



  mydealer() {
    // console.log('Dealer')
  }

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

  geo() {
    this.router.navigateByUrl("geofencing");

  }

  openNav() {
    /* document.getElementById("myNav").style.width = "100%";
    */
    this.router.navigateByUrl("location");

  }

  logout() {
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }
  devi() {
    this.router.navigateByUrl("dashboard");

  }
  soon() {
    this.router.navigateByUrl("const?_i=" + window.localStorage.token);

  }
  new() {
    this.router.navigateByUrl("new");

  }

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

  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");
  }

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

  alert_report() {
    this.cond = false
    this.router.navigateByUrl("device-report/alert-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");

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


  }


  driverPerformance() {
    this.cond = false
    this.router.navigateByUrl("device-report/Driver-performance");
  }
  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");

  }


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

  saveRoute() {
    this.cond = false
    this.router.navigateByUrl('vehicleRoute');
  }


  addcus() {
    localStorage.removeItem('mapLoad_ID')
    this.router.navigateByUrl("add");
  }

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

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

  }


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


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

  }
  routePath: any = [];
  // routeDetails(uId){
  // debugger;
  // console.log("routeDetails",uId);
  // this.contactService.getRouteDetail(uId)
  // .subscribe(res=>{
  // console.log("routedet",res)
  // this.route_detail_show=res;

  // console.log(this.route_detail_show);
  // this.showRoute();
  // })

  // }
  poiPoint_address: any;
  dataArrayCoords = [];
  mapData = [];
  marker: any;
  marker1: any;
  locationEndAddress = []
  PointInterestName = []
  MarkerPointInterest = []
  map: any;
  marker3: any;
  rtePath: any = [];
  markerpoi: any;



  poiMarkers = []
  showRoute(rtePath) {
    // console.log("data coming from routemapping", rtePath);
    var outerThis = this;
    // console.log("Inside function!!!");
    this.dataArrayCoords = [];

    if (rtePath.routePath) {
      for (var i = 0; i < rtePath.routePath.length; i++) {
        var arr = [];
        // console.log(rtePath.routePath[i].location.coordinates[1]);
        arr.push(rtePath.routePath[i].location.coordinates[1]);
        arr.push(rtePath.routePath[i].location.coordinates[0]);

        this.dataArrayCoords.push(arr);
      }
    }
    // console.log(this.dataArrayCoords);
    this.mapData = [];
    if (rtePath.routePath) {
      for (var i = 0; i < rtePath.routePath.length; i++) {


        this.mapData.push({
          "lat": rtePath.routePath[i].location.coordinates[1],
          "lng": rtePath.routePath[i].location.coordinates[0]
        });
      }
    }
    // console.log(this.mapData);


    // variable for rendering current position
    var current_add = new google.maps.LatLng(this.mapData[0], this.mapData[this.mapData.length - 1]);
    this.mapOptions = {
      zoom: 16,
      center: current_add
    };

    // var renderer = new google.maps.DirectionsRenderer({
    // suppressPolylines: true
    // });



    this.globalComponentMap = new google.maps.Map(document.getElementById('showMap'), this.mapOptions);

    this.marker4 = new google.maps.Marker({
      position: {lat:this.latLngLine[0].lat,lng:this.latLngLine[0].lng},
      map: this.globalComponentMap,
      //icon: 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png'
      icon: this.icons.car
  });
  
  var flightPath = new google.maps.Polyline({
    path: this.latLngLine,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });
  
  flightPath.setMap(this.globalComponentMap);
      // console.log(this.flag);


    // this.globalComponentMap = new google.maps.Map(document.getElementById('showMap'), mapOptions);

    // console.log(this.routePath.destination);

    var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/S/009900/ ");
    this.marker = new google.maps.Marker({
      position: this.mapData[0],
      map: this.globalComponentMap,
      icon: pinImage
    });

    var pinImage1 = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/D/FF0000/ ");
    this.marker1 = new google.maps.Marker({
      position: this.mapData[this.mapData.length - 1],
      map: this.globalComponentMap,
      icon: pinImage1
    });

    // console.log()
    if (rtePath.poi) {
      for (var i = 0; i < rtePath.poi.length; i++) {
        this.test = rtePath.poi[i];
        var poiMarker_object = {
          "lat": rtePath.poi[i].poi.location.coordinates[1],
          "lng": rtePath.poi[i].poi.location.coordinates[0]
        }

        var pinImagePOI = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/009900/ ");
        this.markerpoi = new google.maps.Marker({
          position: poiMarker_object,
          map: this.globalComponentMap,
          icon: pinImagePOI
        });
        // console.log(rtePath.poi[i]);

        var infowindow = new google.maps.InfoWindow();
        google.maps.event.addListener(this.markerpoi, 'click', (function (markerpoi, i) {
          // console.log(i);
          return function () {


            infowindow.setContent(outerThis.test.poiname);
            infowindow.open(this.map, outerThis.markerpoi);
          }
        })(this.markerpoi));

      }
    }

    // infiwindows starts here 


    var infowindow = new google.maps.InfoWindow();
    google.maps.event.addListener(this.marker, 'click', (function (marker, i) {
      return function () {
        // console.log(rtePath.source);
        infowindow.setContent(rtePath.source);
        infowindow.open(this.map, outerThis.marker);
      }
    })(this.marker));
    var infowindow = new google.maps.InfoWindow();
    google.maps.event.addListener(this.marker1, 'click', (function (marker1, i) {
      return function () {
        // console.log(rtePath.destination)
        infowindow.setContent(rtePath.destination);
        infowindow.open(this.map, outerThis.marker1);
      }
    })
      (this.marker1)
    );

    // console.log(this.mapData);
    var flightPath = new google.maps.Polyline({
      path: this.mapData,
      geodesic: true,
      strokeColor: '#1E90FF',
      strokeOpacity: 1.0,
      strokeWeight: 6
    });

    // console.log(this.mapData);
    flightPath.setMap(this.globalComponentMap);
    // console.log(flightPath);
    flightPath.addListener('click', showArrays);

    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 latStart = event.latLng.lat();
      var lngStart = event.latLng.lng();

      var lngStart1 = new google.maps.LatLng(latStart, lngStart);
      var geocoder = new google.maps.Geocoder();
      var request = {
        latLng: lngStart1
      };

      geocoder.geocode({
        'latLng': event.latLng
      }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {
            // console.log(results[0].formatted_address);
            outerThis.locationEndAddress = results[0].formatted_address;
            outerThis.PointInterestName.push(outerThis.locationEndAddress)
            // console.log("waypointName", outerThis.PointInterestName)
          }
        }
      });



      var contentString = '<b>Point Of Interest</b><br>' +
        'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() + '<br>' + outerThis.locationEndAddress +
        '<br>';

      // console.log(event.latLng.lat(), event.latLng.lng());

      outerThis.MarkerPointInterest.push([event.latLng.lat(), event.latLng.lng()]);
      // console.log("markerPOI", outerThis.MarkerPointInterest);

      // Replace the info window's content and position.
      var infoWindow = new google.maps.InfoWindow();
      infoWindow.setContent(contentString);
      infoWindow.setPosition(event.latLng);
      infoWindow.open(this.globalComponentMap);
      placeMarker(event.latLng);

      function placeMarker(location) {
        outerThis.marker3 = new google.maps.Marker({
          position: location,
          map: this.globalComponentMap
        });

      }

    }
  }


  payloadArray = [];
  addPOI() {
    // console.log(this.POIPayload.routeId);
    // console.log(this.POIPayload.payload);

    //console.log(this.POIPayload.poi[j].poiname)
    // for (var j = 0; j < this.POIPayload.poi.length; j++) {
    // var b = {
    // "address": this.POIPayload.poi[j].address,
    // "location": {
    // "coordinates": [
    // this.POIPayload.poi[j].location.coordinates[0],
    // this.POIPayload.poi[j].location.coordinates[1]
    // ],
    // "type": "Point"
    // }

    // }

    // this.payloadArray.push(b);

    // }
    this.payloadArray = this.POIPayload.poi;

    for (var i = 0; i < this.MarkerPointInterest.length; i++) {
      if (this.PointInterestName[i] == "" || this.PointInterestName[i] == undefined || this.PointInterestName[i] == null) {
        this.PointInterestName[i] = "";
      }
      var a = {
        "address": this.PointInterestName[i],
        "location": {
          "coordinates": [
            this.MarkerPointInterest[i]["1"],
            this.MarkerPointInterest[i]["0"],
          ],
          "type": "Point"
        }
      }
      this.payloadArray.push(a);
    }

    // console.log(this.payloadArray);
    // console.log(this.POIPayload.routeId);
    var poi_PayLoad = {
      poi: this.payloadArray,
      _id: this.POIPayload.routeId

    }
    // console.log(poi_PayLoad)
    this.contactService.addPOI(poi_PayLoad)
      .subscribe(res => {
        // console.log(res)
        var poiRes = res;
        // console.log(poiRes);
        this.cond = false;

      }, err => {
        // console.log(err.status);
        this.router.navigateByUrl("routeMapping");
      })

  }


  poiWindow() {
    let dialogRef_1 = this.dialog.open(PoiListComponent, {
      height: '500px',
      width: '950px',
      data: { routeId: this.POIPayload.routeId }
    });

  }

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


  getPOI() {
    var rId = this.divehistory.routeId;
    // console.log(rId)
    this.contactService.getPoiReplay(rId, this.useridd)
      .subscribe(res => {
        // console.log(res);
        this.pathObj = res;
     
        this.showRoute(this.pathObj);
       
      }, err => {
        this.getDeviceHistory();
        
        // console.log(err.status);

      })
  }

  speeed2: any = 0;
  speed: any = 200;
  target: number = 0;
  playing: boolean = false;
  inc = 0;
  marker4:any;
 

  // ============================replay functionality==========================================================
  animateMarker(marker, coords, km_h){
   var target = 0;
   var that= this;
  //  console.log(km_h)
      
      coords.push({lat:coords[coords.length-1].lat,lng:coords[coords.length-1].lng});
      
      that._goToPoint =function()
      {

  
         that.speed = that.speed || 50;
        
          var lat = marker.position.lat();
          var lng = marker.position.lng();
          
          var step = (that.speed * 1000 * that.delay) / 3600000; // in meters
      
         
          var dest = new google.maps.LatLng(
         
          coords[target].lat, coords[target].lng);
          
          var distance =
          google.maps.geometry.spherical.computeDistanceBetween(
          dest, marker.position); // in meters
          
          var numStep = distance / step;
          var i = 0;
          var deltaLat = (coords[target].lat - lat) / numStep;
          var deltaLng = (coords[target].lng - lng) / numStep;
          that.speedmeterVal= that.mapData1[target]?(that.mapData1[target][2] + "Kmph"):0;
          that.insertionTime = that.mapData1[target]?that.mapData1[target][3] : ''
         
          // console.log('veh speed',that.speedmeterVal)
          that._moveMarker =function()
          {                 
              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)||(head == NaN)) {
                  
                  that.icons.car.rotation = head
              } 
                  marker.setIcon(that.icons.car);  
                  marker.setPosition(new google.maps.LatLng(lat, lng));
                  that.globalComponentMap.setCenter({ lat: lat, lng: lng });
                  that.start =  setTimeout(that._moveMarker, that.delay);
              }
              else
              {  
              var head = google.maps.geometry.spherical.computeHeading(marker.getPosition(), new google.maps.LatLng(lat, lng));
  
                 if ((head != 0)||(head == NaN)) {
                 
                   that.icons.car.rotation = head
              }
              marker.setIcon(that.icons.car);  

               marker.setPosition(dest);
               that.globalComponentMap.setCenter({ lat: lat, lng: lng });
                  target++;
                  if (target == coords.length){ 
                   // target = 0;
                   that.flag = 'reset';
                    clearTimeout(that.start);
                     }              
                that.start = setTimeout(that._goToPoint, that.delay);
              }
          }
          that._moveMarker();
      }
      that._goToPoint();
  }

showStatus:boolean=false;
play(){
  this.showStatus=true
this.playing=!this.playing;
    if(this.flag == 'init'){

      this.animateMarker(this.marker4,this.latLngLine,20000)
      this.flag = 'stop';
  
    }else
    if(this.flag=='start')
    {
      this._moveMarker();
      this.flag = 'stop';
    }else
    if(this.flag=='stop')
    {
      this.speed = 0;
      clearTimeout(this.start);
      this.flag = 'start';
    }
    if(this.flag == 'reset')
    {

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

  }

  fast(b){
 

              //  console.log(b);
               if(b == 'fast'){
               this.speed += 200;
               
                //  console.log(this.speed)
               }
                if(b == 'slow'){
                  if(this.speed<=200){
                    this.speed=200;

                  }
                 this.speed -= 200;
                  // console.log(this.speed);
               }

   }


   onEmptyPOI(){
    //  console.log("if emptyPOI")
    //  console.log("if emptyPOI",this.latLngLine)
    this.marker4 = new google.maps.Marker({
      position: {lat:this.latLngLine[0].lat,lng:this.latLngLine[0].lng},
      map: this.globalComponentMap,
      //icon: 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png'
      icon: this.icons.car
  });
  
  var flightPath = new google.maps.Polyline({
    path: this.latLngLine,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });
  flightPath.setMap(this.globalComponentMap); 

  
   }

  
  //  ngOnDestroy(){
  //    this.globalComponentMap.setMap(null);
  //  }
  
    // ============================replay functionality==========================================================




  mapData1 = [];
  getDeviceHistory() {
    // console.log(this.divehistory);
    var ftime = this.divehistory ? this.divehistory.actualStartTime : null;
    var ttime = this.divehistory ? this.divehistory.actualEndTime : null;
    var devId = this.divehistory ? this.divehistory.deviceId : null;
    var retrievedData = localStorage.getItem("devices");
    var cord = JSON.parse(retrievedData);
    // console.log("deviceDetail", cord);
    // console.log("deviceHistoryData=>",ftime,ttime,devId);

    if ((ftime == undefined) || (ftime == null) || (ttime == undefined) || (ttime == null)) {
      this.errormsg = "no devicehistory found";
      // console.log(this.errormsg);

    } else {
      // console.log(devId)
      this.contactService.getCurrentLocation(devId, ftime, ttime)
        .subscribe(res => {
         
          // console.log("flight path res", res);

          var rH = res;
          for (let k = rH.length - 1; k > 0; k--) {
            var rhArray = [rH[k].latDecimal, rH[k].longDecimal, rH[k].speed,rH[k].insertionTime];
            this.mapData1.push(rhArray);

            let cord = {
              lat: rH[k].latDecimal,
              lng: rH[k].longDecimal
            }

            this.latLngLine.push(cord);

          }
          // console.log("MarkeraRRray", this.latLngLine)
          this.onEmptyPOI();
        })
    }

  }


}





