import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import {ContactService} from '../contact.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { typeSourceSpan } from '@angular/compiler';
import { Location } from '@angular/common';

declare var google: any;
declare var $:any;

@Component({
  selector: 'app-geofence-add',
  templateUrl: './geofence-add.component.html',
  styleUrls: ['./geofence-add.component.scss'],
  providers: [ContactService]
  
})
export class GeofenceAddComponent implements OnInit {
  grpName: any =[];
  geoT:any;
  geofenceColor :any='#ff0000';
  geoType= ["Loading","Unloading","Parking"];
  fs :any;
  ls:any;
  emailid:any;
  or:any;
  onn_time:any;
  min:any;
  corect_min:any;
  hr:any;
  grp:any;
  shapeRadius: any;
  shapeLocation: { lat: any; lng: any; };
  address: any;
  halt_alert : Boolean = false;
  gMap: any;
  flightPath: any;
  btnTag: string= 'Create';
  geofence_id: string;
  devicesss=[];
  uncheckedArr=[]
  poiDevices=[];
  tempArray: any[];
  untrackedDev=[];
  selectedDevices: any[];
  notSelectedPOIArray=[];
  options: any=[{selectedValue : '',value:''}];
  run(){
  
  }
  data_descip:any;
  tost1(divid){
    if(divid == "Error : Please Select Geo Fence Region"){
      this.data_descip = 'Error : Please Select Geo Fence Region';
      launch_toast();
    }
    else if(divid == "Error : Select Alert Type"){
      this.data_descip ='Error : Select Alert Type';
      launch_toast();
    }
    else if(divid == 'Error : Please enter your Geo Fence name'){
      this.data_descip = 'Error : Please enter your Geo Fence name';
      launch_toast();
    }
    else if(divid == "blankemail"){
      this.data_descip = "Blank Email ID or Mobile Number";
      launch_toast();
    }
    else if(divid == "deleteshareDevice"){
      this.data_descip = "Share Device Succesfully Removed";
      
      launch_toast();
    }
    else if(divid == "removeuser"){
      this.data_descip = "Share Device User Succesfully Removed";
      
      launch_toast();
    }
    else if(divid == "No_Dev"){
      this.data_descip = "No Shared Users for this Device";
      
      launch_toast();
    }
    else if(divid == "device_alert"){
      this.data_descip = "Speed Alert Sucessfully Added";
      launch_toast();
    }
    else if(divid == "NotSucc"){
      this.data_descip = "Speed Alert Removed";
      launch_toast();
    }
    else if(divid == "new_Device"){
      window.localStorage['FinalAddDevice'] = 'False'
      this.data_descip = "New Device Added";
      launch_toast();        
    }else if(divid == 'Error : Please Select Group'){
      window.localStorage['FinalAddDevice'] = 'False'
      this.data_descip = "Please Select Group";
      launch_toast();
    }else if(divid === "Error : Please Select Geofence type"){
      window.localStorage['FinalAddDevice'] = 'False'
      this.data_descip = "Please Select Geofence type";
      launch_toast();
    }else if (divid === "Error : Please create Geo Fence"){
      window.localStorage['FinalAddDevice'] = 'False'
      this.data_descip = "Please create Geo Fence";
      launch_toast();
    }else if (divid === "deleteFirst"){
      this.data_descip = "Recreate Geofence first";
      launch_toast();
    }
      function launch_toast() {
       // console.log(divid);
        var x = document.getElementById("toast")
        //console.log(x);
        x.className = "show";
        setTimeout(function(){ x.className = x.className.replace("show", ""); }, 2500);
    }
     }
  myaccount(){
   
    let dialogRef = this.dialog.open(MyaccountComponent, {
      width: '903px',
      data: {}
    });
  
    dialogRef.afterClosed().subscribe(result => {
  
      if(result == "succ"){
        // console.log("Updated")
      }
  
    });
  }
 
    constructor(public loaction:Location,private router: Router ,private contactService:ContactService,private _flashMessagesService: FlashMessagesService,public dialog: MdDialog) {
   
     }

    mydealer(){
      window.localStorage['token'] =  window.localStorage['Dealer_token'];
      localStorage.removeItem('devices');
      window.localStorage['DataUpdate'] = 'True';
      if(window.localStorage['DataLoaded'] = 'True'){
        window.localStorage['Custumer'] = 'OFF'
        this.router.navigateByUrl("add")
       // this.router.navigateByUrl("const?_status="+"OK");
      }
    }
    cond:Boolean = false;
    point : any = 0;
    
    devicess:any;
    final:any;
    getdev(){
      let foods = []
      this.contactService.getDevice(this.emailid,this.useridd).subscribe(
          
        data => {
          this.devicess = data.devices ;
          console.log("IN DEVICE___",this.devicess);
          

          for(let i=0;i<this.devicess.length;i++){
              let a ={
                value : this.devicess[i].Device_Name,
                viewValue:this.devicess[i].Device_Name,
                did:this.devicess[i].Device_ID,
                id:this.devicess[i]._id,
                user:this.devicess[i].user,
               
              }
             
                a['selectedValue'] = this.devicess[i]._id ; 
                this.options.push(a);
              }

    
        });
    }

    geoname:any = null;
    new:any = null;
    enter:any;
    exit:any;
    geoadd:any;
    before:any;
    haltAlert:number = 60;
    creategeo(){

      if(this.flightPathArr.length != 0){
        this.tost1('deleteFirst');
        return;
        

      }
     
      // var grp =  $('#dbselect').multipleSelect('getSelects','value'); 
      var geoType =  $('#dbselect_1').multipleSelect('getSelects','value'); 
      var retrievedData = localStorage.getItem("cordinates");
      var cord = JSON.parse(retrievedData);   
      // console.log(grp,geoType);
     
      // if((grp === undefined)||(grp.length === 0)){
      //    this.tost1('Error : Please Select Group');
      // }
      // else 
      if((geoType === undefined)||(geoType.length === 0)){
        this.tost1('Error : Please Select Geofence type');
      }         
      else if((cord == null || cord == undefined) && (this.shapeIdentifier == 'polygon')){
       /*  this._flashMessagesService.show('Error : Please Select Geo Fence Region', { cssClass: 'alert-danger', timeout: 2000 });   */
        this.tost1('Error : Please Select Geo Fence Region')
      }
      else if(this.enter == false && this.exit == false){
     /*    this._flashMessagesService.show('Error : Select Alert Type', { cssClass: 'alert-danger', timeout: 2000 });  */ 
        this.tost1('Error : Select Alert Type')
      }
      else if(this.geoname == null || this.geoname == undefined){
      /*   this._flashMessagesService.show('Error : Please enter your Geo Fence name', { cssClass: 'alert-danger', timeout: 2000 });  */
        this.tost1('Error : Please enter your Geo Fence name') 
      }else if(this.shapeIdentifier === undefined){
        this.tost1('Error : Please create Geo Fence') 
      }
      else{

        // console.log("Coordinates",cord);    
   
        if (this.shapeIdentifier === 'polygon') {
          const newGeo ={
            uid: this.useridd,
            geofence:cord,
            geoname: this.geoname,
            entering:this.enter,
            exiting:this.exit,
            // vehicleGroup:grp[0],
            type:geoType[0],
            // untrackedDevice:this.notSelectedPOIArray      
          }

          if(this.halt_alert === true){
            newGeo['halt_notif'] = this.halt_alert ; 
            newGeo['halt_time'] = JSON.stringify(this.haltAlert) ; 
          }else{
            newGeo['halt_notif']  = false; 
          }

          if(this.btnTag === 'Create'){
            // newGeo['untrackedDevice']=this.notSelectedPOIArray 
            console.log("NEEJDKJ",newGeo);
            
            this.contactService.addGeo(newGeo).subscribe(devgeo => {
              localStorage.removeItem("cordinates");
              this.router.navigateByUrl("geofencing");
              this.geoadd.push(devgeo);
            }, (err: any) => { 
  
            });
          }

          if(this.btnTag === 'Update'){
      
            newGeo['_id'] = this.geofence_id;
            this.contactService.updateGeo(newGeo).subscribe(devgeo => {
              localStorage.removeItem("cordinates");
              this.router.navigateByUrl("geofencing");
              // this.geoadd.push(devgeo);
            }, (err: any) => { 
  
            });
          }

        }


        if (this.shapeIdentifier === 'circle') {
          var circleObj = 
          {
            "poi": [
              {
                "location": {
                  "type": "Point",
                  "coordinates": [
                    this.shapeLocation.lat,
                    this.shapeLocation.lng
                  ]
                },
                "poiname": this.geoname,
                // "group" : grp[0],
                "status": "Active",
                "user": this.useridd,
                "address":  this.address,
                "radius":  this.shapeRadius ,
                "entering":this.enter,
                "exiting":this.exit
              }
            ]
          }
          
          if(this.halt_alert === true){
            circleObj['halt_notif'] = this.halt_alert ; 
            circleObj['halt_time'] = JSON.stringify(this.haltAlert) ; 
          }else{
            circleObj['halt_notif']  = false; 
          }

            this.contactService.addOnePoi(circleObj).subscribe(poiResp => {
              console.log('poiResp',poiResp);
              localStorage.removeItem("cordinates");
              this.router.navigateByUrl("geofencing");
              // this.geoadd.push(devgeo);
            }, (err: any) => { 
              console.log(err);
            });
        }
    }

      //this.showgeo();

    }
  
    showgeo(){
      var that =this;
       let map;
       let cord = [];
       let finalcord = [];
      var outerThis= this;
      // console.log("Running GEO")
      if (navigator.geolocation) {  
       
        if(location.protocol != 'https:'){
          console.log('https nahi hai');

          this.contactService.getlatLong().subscribe(res=>{
            console.log(res);
            var position = {
              coords: { 
                latitude: res.lat,
                longitude: res.lon
              }
            };

         

            this.getAddress(res.lat,res.lon);

            map = new google.maps.Map(document.getElementById('map'), {
              center: {
                  lat: position.coords.latitude,
                  lng: position.coords.longitude
              },
            
              zoom: 18
          });    
          that.gMap = map;
          drawPoly();
            this.geofenceFunction(map,finalcord,cord,position)
          })
        }else{
          console.log('https hai');

          navigator.geolocation.getCurrentPosition(function(position) {
              
            map = new google.maps.Map(document.getElementById('map'), {
                center: {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                },
            
                zoom: 18
            });
            that.gMap = map;
            drawPoly();
            outerThis.getAddress(position.coords.latitude,position.coords.longitude)
            outerThis.geofenceFunction(map,finalcord,cord,position)

        });
        }

            }

            function drawPoly(){
            
              if(that.flightPathArr.length !=0){
                console.log('that.flightPathArr',that.flightPathArr);
                that.flightPath = new google.maps.Polyline({
                  path: that.flightPathArr,
                  geodesic: true,
                  fillColor:'red',
                  strokeColor: "#0000FF",
                  strokeOpacity: 1.0,
                  strokeWeight: 6
                });
      
                map.setCenter(new google.maps.LatLng(that.flightPathArr[0].lat, that.flightPathArr[0].lng));
                that.flightPath.setMap(map);
              }
            
    
            }
    }
  
    shapeIdentifier: any;
    mainMarker:any;
  geofenceFunction(map, finalcord, cord,position) {
    var that = this;
    var myLatLng = {
      lat :position.coords.latitude,
      lng : position.coords.longitude
    }
  
    
   this.mainMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: JSON.stringify({Latitude : position.coords.latitude, Longitude : position.coords.longitude})
    });

    this.mainMarker.setMap(map);
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    

    map.addListener('bounds_changed', function () {
      searchBox.setBounds(map.getBounds());
    });

    var markers = [];

    searchBox.addListener('places_changed', function () {
      var places = searchBox.getPlaces();
      if (places.length == 0) {
        return;
      }

     that.address = places.formatted_address ; 
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function (place) {
        if (!place.geometry) {
          return;
        }


        that.mainMarker.setMap(null);
        var latLngM = {
          lat : place.geometry?place.geometry.location.lat():null,
          lng : place.geometry?place.geometry.location.lng():null, 
        } 

         
        that.mainMarker = new google.maps.Marker({
          position: latLngM,
          map: map,
          title: JSON.stringify({Latitude : latLngM.lat, Longitude : latLngM.lng})
        });
  
        that.mainMarker.setMap(map);

        
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };



        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);
    });


    var all_overlays = [];
    var selectedShape;
    if(this.btnTag === 'Update'){
      var drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
          position: google.maps.ControlPosition.TOP_CENTER,
          drawingModes: [
            
            google.maps.drawing.OverlayType.POLYGON
          ]
        },
        markerOptions: {
          icon: 'images/beachflag.png'
        },
  
        polygonOptions: {
          clickable: true,
          draggable: true,
          editable: true,
          fillColor: '#ffff00',
          fillOpacity: 1,
  
        },
        rectangleOptions: {
          clickable: true,
          draggable: true,
          editable: true,
          fillColor: '#ffff00',
          fillOpacity: 0.5,
        }
      });
    }else{
      var drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
          position: google.maps.ControlPosition.TOP_CENTER,
          drawingModes: [
            google.maps.drawing.OverlayType.CIRCLE,
            google.maps.drawing.OverlayType.POLYGON
          ]
        },
        markerOptions: {
          icon: 'images/beachflag.png'
        },
        circleOptions: {
          fillColor: '#ffff00',
          fillOpacity: 0.2,
          strokeWeight: 3,
          clickable: false,
          editable: true,
          zIndex: 1
        },
        polygonOptions: {
          clickable: true,
          draggable: true,
          editable: true,
          fillColor: '#ffff00',
          fillOpacity: 1,
  
        },
        rectangleOptions: {
          clickable: true,
          draggable: true,
          editable: true,
          fillColor: '#ffff00',
          fillOpacity: 0.5,
        }
      });
    }
    var drawingManager = new google.maps.drawing.DrawingManager({
      drawingMode: google.maps.drawing.OverlayType.MARKER,
      drawingControl: true,
      drawingControlOptions: {
        position: google.maps.ControlPosition.TOP_CENTER,
        drawingModes: [
          google.maps.drawing.OverlayType.CIRCLE,
          google.maps.drawing.OverlayType.POLYGON
        ]
      },
      markerOptions: {
        icon: 'images/beachflag.png'
      },
      circleOptions: {
        fillColor: '#ffff00',
        fillOpacity: 0.2,
        strokeWeight: 3,
        clickable: false,
        editable: true,
        zIndex: 1
      },
      polygonOptions: {
        clickable: true,
        draggable: true,
        editable: true,
        fillColor: '#ffff00',
        fillOpacity: 1,

      },
      rectangleOptions: {
        clickable: true,
        draggable: true,
        editable: true,
        fillColor: '#ffff00',
        fillOpacity: 0.5,
      }
    });

    function clearSelection() {
      if (selectedShape) {
        selectedShape.setEditable(false);
        selectedShape = null;
      }
    }

    function setSelection(shape) {
      console.log('abc');
      clearSelection();
      selectedShape = shape;
      shape.setEditable(true);
      if(that.shapeIdentifier === 'polygon'){
    
        google.maps.event.addListener(selectedShape.getPath(), 'set_at', getPolygonCoords(shape));
      } 
    }

    function deleteSelectedShape() {
      if(that.flightPathArr.length != 0){
        that.flightPathArr=[];
        that.flightPath.setMap(null);

      }
      console.log('deleteButtonClicked')

      if (selectedShape) {
        selectedShape.setMap(null);
      }
      finalcord = [];
      cord = [];
    }

    function deleteAllShape() {
      for (var i = 0; i < all_overlays.length; i++) {
        all_overlays[i].overlay.setMap(null);
        }
      all_overlays = [];
      finalcord = [];
      cord = [];
    }
    var that = this;
    function CenterControl(controlDiv, map) {

      // Set CSS for the control border.
      console.log('controlUI',controlUI);
      map.controls[google.maps.ControlPosition.BOTTOM_CENTER].clear();
    
        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 = 'center';
        controlUI.title = 'Select to delete the shape';
        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 = 'Delete Selected Area';
        controlUI.appendChild(controlText);
        // Setup the click event listeners: simply set the map to Chicago.
        controlUI.addEventListener('click', function () {
          deleteSelectedShape();
          localStorage.removeItem("cordinates");
        });
      

     
     

    }
    drawingManager.setMap(map);
    var getPolygonCoords = function (newShape) {
      //  console.log("We are one");
      console.log('abc');
      console.log('newShape', newShape);
      var len = newShape.getPath().getLength();

      for (var i = 0; i < len; i++) {
      
        let b = newShape.getPath().getAt(i).toUrlValue(6)
        //console.log(b)
        let a = [
        ]
        a.push(parseFloat(b.split(",")[1]))
        a.push(parseFloat(b.split(",")[0]))
        cord.push(a);

      }
      let p = cord[0];
      cord.push(p);
      finalcord.push(cord)   
      let val = JSON.stringify(finalcord);  
      localStorage.setItem("cordinates", val);
    };

    google.maps.event.addListener(drawingManager, 'polygoncomplete', function (event) {
      if(that.flightPathArr.length!=0){
        that.flightPathArr=[];
        that.flightPath.setMap(null);

      }
      event.getPath().getLength();
      google.maps.event.addListener(event.getPath(), 'insert_at', function () {
        var len = event.getPath().getLength();
        for (var i = 0; i < len; i++) {
        
        }
      });
      google.maps.event.addListener(event.getPath(), 'set_at', function () {
        console.log('abc');
        var len = event.getPath().getLength();
        for (var i = 0; i < len; i++) {
          //  console.log(event.getPath().getAt(i).toUrlValue(5));
        }
      });
    });


    google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {  
      console.log('abc');
      // console.log('circleComplete');
      console.log(event);
      event.overlay.fillColor = that.geofenceColor ; 
     
      
      all_overlays.push(event);
      if (event.type !== google.maps.drawing.OverlayType.MARKER) {
        console.log(event.overlay);
        drawingManager.setDrawingMode(null);
        //Write code to select the newly selected object.
        var newShape = event.overlay;
        newShape.type = event.type;
        that.shapeIdentifier = event.type; 
        console.log(that.shapeIdentifier);  
        google.maps.event.addListener(newShape, 'click', function () {
          console.log(newShape);
          setSelection(newShape);
        });   
          setSelection(newShape);    
      }   
    });


    // =================================circle listner =======================================
    google.maps.event.addListener(drawingManager, 'circlecomplete', function (event) {
    
      console.log('abc');
      var newShape_circle = event;
      console.log(newShape_circle);

      var circle;
      if (event == null || (!(event instanceof google.maps.Circle))) return;
      if (circle != null) {
        circle.setMap(null);
        circle = null;
      }
      circle = event;
      console.log('radius', circle.getRadius());
      console.log('lat', circle.getCenter().lat());
      console.log('lng', circle.getCenter().lng());
      that.shapeRadius = circle.getRadius() ; 
      that.shapeLocation = {
        lat : circle.getCenter().lat(),
        lng : circle.getCenter().lng()
      }

      console.log('that.shapeLocation=>',that.shapeLocation);
     
    });

    var centerControlDiv = document.createElement('div');
    var centerControl = new CenterControl(centerControlDiv, map);
    map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(centerControlDiv);

  }



  useridd:any;

  foods=[]
  custtype:any;
  cust:boolean=false;
  ideal(){
    this.router.navigateByUrl("device-report/ideal-report");
  }
  mb:any;
  logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
superAdmin:Boolean = false;
    ngOnInit() {
       var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
  script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
  document.getElementsByTagName("head")[0].appendChild(script);
  setTimeout(() => {
    // $('#dbselectIMEI').multipleSelect({
        //   width: 250,
        //   placeholder: "Vehicle IMEI",
        //   filter: true,
        //   single: true,
        //   selectAll: false  
        // }) 
  
        $('#dbselectVehicleName').multipleSelect({
          width: 250,
          placeholder: "Vehicle Name",
          filter: true,
          single: true,
          selectAll: false  
        }) 
        
        // $("#dbselectVehicleName").multipleSelect("disable");
        
      },100)
      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.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
      this.getdev();
      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.logo=window.localStorage['logo'];
    this.text=window.localStorage['text'];
    
      this.enter=false;
      this.exit=false

     

        let geofence_id =window.location.search;
        var that= this;
        if(geofence_id != ''){
          let gid = JSON.stringify(geofence_id).split("=")[1].split('"')[0];
          this.geofence_id = gid;
          this.btnTag = 'Update';
          this.contactService.getperGeoFence(gid).subscribe(geoObj=>{
            console.log(geoObj);
          
              this.geoname = geoObj[0].geoname;
              this.halt_alert= geoObj[0].halt_notif?geoObj[0].halt_notif:false;
              this.haltAlert = geoObj[0].halt_time?geoObj[0].halt_time:false;
              this.enter = geoObj[0].entering;
              this.exit=geoObj[0].exiting;
              this.shapeIdentifier = 'polygon';
              
              // outerThis.flightPathArr.push({ lat: msg.latDecimal, lng: msg.longDecimal }); 
              var latLngArr = geoObj[0].geofence.coordinates?geoObj[0].geofence.coordinates[0]:[];
              console.log('latLngArr',latLngArr);
              for(var i=0;i<latLngArr.length;i++){
                this.flightPathArr.push({ lat:latLngArr[i][1], lng: latLngArr[i][0] });
              }     
              // var drawPath = setTimeout(()=>{
              //   that.drawFlightPath();
              //   clearTimeout(drawPath);
              // },5000)
              this.showgeo();
          })
        }else{
          this.showgeo();
        }
   
     

        this.loadropdown();
        this.getGrp();
        this.getUserDevices();
        this.getDevices()
       
    }
    getDevices(){
       this.contactService.getDevice(this.emailid,this.useridd).subscribe(
        
        data => {
          this.devicess = data 
         /*  this.final = this.devicess.devices[0]; */
         this.final = (this.devicess.devices);
        
         for(let i=0;i<this.devicess.devices.length;i++){
         
           if(this.devicess.devices[i].type_of_device =="Tracker"){
             let a ={
              value : this.devicess.devices[i].Device_Name,
              viewValue:this.devicess.devices[i].Device_Name,
              did:this.devicess.devices[i].Device_ID,
              id:this.devicess.devices[i]._id,
              user:this.devicess.devices[i].user,
              email:this.devicess.devices[i].Email_ID,
             }
             this.foods.push(a);
           }
        
         }
    
        });
    }
    // summaryReport(){
   
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/summary-report");
    // }
    
    // geofancingReport(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/geofancing");
    // }
    
    // distance_report(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/distance_report");
    // }
    
    // alert_report(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/alert_report");
    // }
    
    // trip_report(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/trip_report");
    
    // }
    
    // overspeed(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/overspeed");
    
    // }
    // stoppage_report(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/stoppage_report");
    
    // }
    
    // group(){
    //   this.cond = false
    //   this.router.navigateByUrl("group_view");
    // }
    
    // ignition_report(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/ignition_report");
    
    
    // }
    
    // routeViolation(){
    //   this.cond = false
    //   this.router.navigateByUrl("device-report/routeViolation");
    
    // }

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

  
    getGrp(){
      this.contactService.getGroup(this.useridd).subscribe(      
        res => {
          // console.log(res);     
          this.grpName = res["group_details"];
          console.log(this.grpName);
          this.loadropdown();
        })
    }

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

    loadropdown() {
      var script = document.createElement("script");
      script.setAttribute("type", "text/javascript");
      script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
      document.getElementsByTagName("head")[0].appendChild(script);
        setTimeout(() => {
          $('#dbselect').multipleSelect({
            width: 230,
            placeholder: 'Select Group',
            filter: true,
            single: true,
            selectAll: false
     
          })
        }, 100);
        setTimeout(() => {
          $('#dbselect_1').multipleSelect({
            width: 230,
            placeholder: 'Select Geofence type.....',
            filter: true,
            single: true,
            selectAll: false
     
          })
         // $('#select').show();
      
        }, 100);
    }


    getAddress(lat,lng){
     var outerThis = this;
      let latLng = {
        lat: "0",
        long: "0"
      };
        latLng = {
          lat: lat ? lat : 0,
          long: lng ? lng : 0
        }
        this.contactService.getAddressByApi(latLng).subscribe(res=>{   
  
          if(res.message == "Address not found in databse"){
            let geocoder = new google.maps.Geocoder();
            let t_latlng = new google.maps.LatLng(lat, lng);
      
            let request = {
              latLng: t_latlng
            };
            geocoder.geocode(request, function (data, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                if (data[0] != null) {
                  // outerThis.address_show = data[0].formatted_address;
                  document.getElementById('pac-input').setAttribute("value", data[0].formatted_address);  
                  outerThis.address = data[0].formatted_address ; 
                } else {
                  // console.log("No address available")            
                  document.getElementById('pac-input').setAttribute("value", 'NA');  
                  outerThis.address = 'NA';
                }
              }
              else {
                document.getElementById('pac-input').setAttribute("value", 'NA'); 
                outerThis.address = 'NA'; 

              }
            })
          }else{
            document.getElementById('pac-input').setAttribute("value", res.address);  
            outerThis.address = res.address;
          }
        })

    }
    flightPathArr=[];
    // drawFlightPath(){
    //   console.log('inside flightpathDraw',this.flightPathArr);
    //   var flightPath = new google.maps.Polyline({
    //     path: this.flightPathArr,
    //     geodesic: true,
    //     strokeColor: "#0000FF",
    //     strokeOpacity: 1.0,
    //     strokeWeight: 6
    //   });
    //   // //console.log(mapData);
    //   flightPath.setMap(this.gMap);
    // }

 getUserDevices(){
    this.contactService.getDevice(this.emailid,this.useridd).subscribe(
      data => {
        this.devicesss = data.devices;
        console.log("deviceObj=>",this.devicesss);
        for(var i = 0; i<data.devices.length ; i++){       
            var dev = {
              isTrue:false,
              id:data.devices[i]._id,
              deviceName: data.devices[i].Device_Name
            }  

          this.uncheckedArr.push(dev);  
          this.poiDevices.push(dev);          
        }   

          var newArr = [];
          for(var t = 0 ;t<this.untrackedDev.length;t++){
            for(var n=0;n<this.uncheckedArr.length;n++){
              if(this.untrackedDev[t]==this.uncheckedArr[n].id){
               
                // this.poiDevices[n].isTrue = true;  
                // console.log("newArr=>",this.poiDevices);  
                this.uncheckedArr.splice(n,1);
             
              }
            }
             }
              var tarr =[];
             for(var l = 0;l<this.uncheckedArr.length;l++){     
               tarr.push(this.uncheckedArr[l].id);
               this.tempArray = tarr;            
             }
            console.log("whats here =>",this.tempArray );
           console.log("bigger deviceArr =>",this.poiDevices);
        
     
        this.selectedDevices = this.tempArray;
        
      },err=>{
      
        console.log(err);
      });
  }

   change(obj: any,ind:any){ 
    this.poiDevices[ind].isTrue = this.poiDevices[ind].isTrue?!this.poiDevices[ind].isTrue:true;
    var i = this.notSelectedPOIArray.indexOf(obj.id);
    
    if( i==-1)
      this.notSelectedPOIArray.push(obj.id);
    else{
      
        this.notSelectedPOIArray.splice(i,1);  
    }
      console.log(this.notSelectedPOIArray); 
  }

  }
  

