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

declare var google: any;
declare var $:any;
@Component({
  selector: 'app-route-set',
  templateUrl: './route-set.component.html',
  styleUrls: ['./route-set.component.scss']
})
export class RouteSetComponent implements OnInit {
  superAdmin: any;
  speed_alert:boolean=true;
  speedAlert:any;
  destination_route: any;
  sourceRoute: any;
  before:any;
  fieldArr=[];
  logoutbut:boolean;
  cust:boolean=false;
  logo:any;
  auto:any;
  myControl: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;
  routeName:any;
  deviceId:any;
  device_update:any;
  dbMap:any;
  options: any;
  deviceArr: any=[];
   count = 0;
  directionsDisplay: any;
  ll: { location: any; stopover: boolean; };
  wapointArray: any[];
  
  constructor(private router: Router,private contactService: ContactService,public dialog: MdDialog) {
      }

  ngOnInit() {
    this.loadropdown();
    // var inputId =  'address' +  this.count++; 
    // var t = {
    //   aid: inputId
    // }
    
    // this.fieldArr.push(t);
    // var temp = setTimeout(()=>{
    //   this.fieldArr[0]['address'] = new google.maps.places.Autocomplete(document.getElementById(inputId))
    //   clearTimeout(temp);
    // },5000)
  
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.logo=window.localStorage['logo'];
    this.text=window.localStorage['text'];  
     window.localStorage['DataUpdate'] = 'True'
    
   
     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;

     if(this.custtype == true){
      this.cust = true;
    }  

    let  foods = [ ];
 
    if(this.mb.charAt(0)=="n"){
     this.mb = ' '
   }
   if( window.localStorage['Custumer'] == 'ON'){
     this.logoutbut = false
     this.dealer = true
  }
  else{
      this.logoutbut = true
  }



    this.contactService.getDevice(this.emailid,this.useridd).subscribe(

      data => {
      var devicesss = data
   
        this.options = [];
      
        for(let i=0;i<devicesss.devices.length;i++){

          // if(devicesss.devices[i].type_of_device =="Tracker"){
            let a ={
              value : devicesss.devices[i].Device_Name,
              viewValue:devicesss.devices[i].Device_Name,
              did:devicesss.devices[i].Device_ID,
              id:devicesss.devices[i]._id,
              user:devicesss.devices[i].user,
              // email: devicesss.devices[i].Email_ID,
              // deviceType: devicesss.devices[i].type_of_device,      
            }
            a['selectedValue'] = devicesss.devices[i]._id ; 
        
            this.options.push(a);
          // }
        }

     
          this.loadropdown();
        

      
          // console.log("ignition option",this.options);
          let that = this;
          // setTimeout(()=>{ 
          // },100)  
      
      });

    

  

  this.initMap();

  }
  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: 200,
        placeholder: 'Select Vehicle',
        filter: true,
 
      })
  
   
    }, 100);
 
  }



// ===========================
sourceAddress:any;
autocompleteSource:any;
inputDestination:any;
autocompleteDestination:any;
// directionsDisplay:any;
// directionsService:any;
source_address:any;
destination_address:any;
source_add:any;
dest_add:any;
polyArray=[];
finlCoords=[];
path=[];
curr_position:any;
initMap() {
var outerThis=this;

  if (navigator.geolocation) {

    if(location.protocol != 'https:'){
      this.contactService.getlatLong().subscribe(res=>{
        console.log(res);
        outerThis.curr_position = {
         
            lat: res.lat,
            lng: res.lon
          
        };

        outerThis.dbMap = new google.maps.Map(document.getElementById('mapp'), {
          center: {
              lat:  outerThis.curr_position.lat,
              lng:  outerThis.curr_position.lng
          },
          zoom: 18
      });    

      var infoWindow = new google.maps.InfoWindow;
      infoWindow.setPosition(outerThis.curr_position);
      infoWindow.setContent('Current location');
      infoWindow.open(outerThis.dbMap);
      outerThis.dbMap.setCenter(outerThis.curr_position);
       
      })
    }
    else{
      navigator.geolocation.getCurrentPosition(function(position) {   
        outerThis.curr_position = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        }  
        // console.log(outerThis.curr_position);
  
        outerThis.dbMap = new google.maps.Map(document.getElementById('mapp'), {
          center: {lat:  outerThis.curr_position.lat, lng: outerThis.curr_position.lng},
          zoom: 15
        });
  
      var infoWindow = new google.maps.InfoWindow;
        infoWindow.setPosition(outerThis.curr_position);
        infoWindow.setContent('Current location');
        infoWindow.open(outerThis.dbMap);
        outerThis.dbMap.setCenter(outerThis.curr_position);
     
      }) 

    }
  

   }
 
   this.source_address = new google.maps.places.Autocomplete(document.getElementById('txtSource'));
   this.destination_address = new google.maps.places.Autocomplete(document.getElementById('txtDestination'));

   google.maps.event.addListener(this.destination_address, 'place_changed', function() {
    console.log("inside place changed function");
  var latLng =  outerThis.destination_address.getPlace().geometry.location;
  console.log('latLng',latLng);
    outerThis.ll ={
      location : new google.maps.LatLng(latLng.lat(),latLng.lng()),
      stopover:false
    }
    // outerThis.waypoints.push(ll);  
    
}) 

   
}


acc_position:any;
waypoints:any;
getRoute(){
  this.waypoints =[];
  var outerThis=this;
  this.source_address = document.getElementById('txtSource');

  debugger;
  console.log('this.fieldArr',this.fieldArr.length);
  if(this.fieldArr.length == 1){
    
    this.waypoints.push(this.ll);  
  }else{
    this.waypoints.push(this.ll);
        for(var k = 0; k<this.fieldArr.length-1 ;k++){
         
       
          if(this.fieldArr[k].latLng!=undefined){
            var pp = {
              location : new google.maps.LatLng(this.fieldArr[k].latLng.lat(),this.fieldArr[k].latLng.lng()),
              stopover:false
            }
  
            outerThis.waypoints.push(pp);  
          }
 
        }
  }
  console.log('outerThis.waypoints',this.waypoints);
  // var destination_address= document.getElementById('txtDestination');
    var ds = document.getElementById('txtDestination');
  if(this.fieldArr.length >0){
    // this.destination_address = document.getElementById(this.fieldArr[this.fieldArr.length -1]['aid']);
    var ps = document.getElementById(this.fieldArr[this.fieldArr.length -1]['aid']);
  
  }

  this.sourceRoute=this.source_address.value;
  console.log(this.sourceRoute);  
  this.destination_route = (this.fieldArr.length >0)?ps['value']:ds['value'];
  console.log(this.sourceRoute,this.destination_route)
  // this.way_point_value = this.waypoints_address.value;

//  console.log
  // var current_add_1 = new google.maps.LatLng(outerThis.curr_position.lat, outerThis.curr_position.lng);
  var mapOptions = {
      center: {lat:  this.curr_position.lat, lng: this.curr_position.lng},
      zoom: 15,
     
  };

  
var map = this.dbMap;
if(outerThis.directionsDisplay != undefined) { 
 
  outerThis.directionsDisplay.setMap(null);
  outerThis.directionsDisplay = null;
 }
var directionsService = new google.maps.DirectionsService;
 outerThis.directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map, 
  });
  google.maps.event.addListener(outerThis.directionsDisplay, 'click', function(h) {
    // console.log(h.latLng.lat(),h.latLng.lng());
  });

  outerThis.directionsDisplay.addListener('directions_changed', function() {
    outerThis.computeTotalDistance(outerThis.directionsDisplay.getDirections());
  });  

  this.displayRoute(this.sourceRoute, this.destination_route, directionsService,outerThis.directionsDisplay,map,this.waypoints)

 }

 

  waypoints_path = [];
  overview_path_latlng = [];

//  method for total display route 

  displayRoute(origin, destination, service, display,map,waypts) {
    console.log('origin=>',origin);
    console.log('destination=>',destination);

var outerThis = this;
  service.route({
    origin: origin,
    destination: destination, 
    waypoints:waypts,
    travelMode: 'DRIVING',   
    avoidTolls: true
  }, function(response, status) {
    if (status === 'OK') {
      outerThis.path=[];
      outerThis.overview_path_latlng=[];
      display.setDirections(response);
      // console.log(response);
      // var currentRoute = currentRouteArray.overview_path;
       var currentRouteArray = response.routes[0].overview_path;
      //  console.log(currentRouteArray);
       for(var i = 0 ; i<currentRouteArray.length;i++){

       var routePath = {
          lat:currentRouteArray[i].lat(),
          lng:currentRouteArray[i].lng()
        }
        outerThis.path.push(routePath);
      }
      outerThis.overview_path_latlng = outerThis.path;
      // console.log(outerThis.overview_path_latlng);

      display.addListener('directions_changed', function() {    
      //  outerThis.addInfo();
      console.log("Inside Direction changed");
       var t  =  display.getDirections();
      //  console.log(t);

       var overview_path = t.routes[0].overview_path
       
            // console.log(overview_path);

            // console.log(t.request.waypoints);
            outerThis.waypoints_path=[];
            outerThis.overview_path_latlng=[];
            outerThis.wapointArray=[];

       for(var j = 0 ; j<t.request.waypoints.length;j++){
         var waypointLatlng = {
           lat:t.request.waypoints[j].location.lat(),
           lng:t.request.waypoints[j].location.lng()
         }
       outerThis.waypoints_path.push(waypointLatlng);
       }
       console.log('outerThis.waypoints_path',outerThis.waypoints_path);
      
       for(var k = 0 ; k<overview_path.length;k++){
        var pathLatLng = {
          lat:overview_path[k].lat(),
          lng:overview_path[k].lng()
        }

        outerThis.overview_path_latlng.push(pathLatLng);
      }   

      console.log('outerThis.overview_path_latlng.push(pathLatLng)', outerThis.overview_path_latlng.push(pathLatLng));

      //  console.log("pathLatlng",outerThis.overview_path_latlng);

      //  console.log("Waypoints" ,outerThis.waypoints_path);    
         });   
      // function for get lat long array ends here 

    } else {
      // console.log('error in display route!!!')
      alert('Could not display directions due to: ' + status);
    }
  });

}
// method for calculate total distance 
 computeTotalDistance(result) {
  var total = 0;
  var myroute = result.routes[0];
  for (var i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }
  total = total / 1000;
  document.getElementById('total').innerHTML = total + ' km';
}
rName:any;
data_descip:any;
emmnerr:any;
tost1(divid){
  if(divid == "routeErr"){
    this.data_descip =  "Please select route "
     launch_toast();
   }
   else if(divid == "rnameErr"){
     this.data_descip =  "Please type route name"
     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", ""); }, 4500);
   }
    }

payloadArray=[];
callDis(data){
  
  this.contactService.addPOICol(data).subscribe(resp=>{
    // console.log("add poi",resp);
   
  })
}
saveRoute(){
  let that = this;
  this.payloadArray=[];
  this.finlCoords=[];
  this.rName;
  // console.log(this.rName)
  this.sourceRoute;this.destination_route;
  if((this.sourceRoute==undefined)||(this.destination_route==undefined)||(this.sourceRoute==null)||(this.destination_route==null)){
    // console.log("Please select route !!!");
    this.tost1("routeErr");

  }
  else if((this.rName==undefined)||(this.rName==null)){
    // console.log("Please select route name");
    this.tost1("rnameErr");
  }
  else{
    this.deviceArr=[];
    this.deviceArr =  $('#dbselect').multipleSelect('getSelects','value'); 
    console.log(this.deviceArr);
    for(var j=0;j<this.overview_path_latlng.length;j++){
    var lattitude = this.overview_path_latlng[j].lat;
    var longitude = this.overview_path_latlng[j].lng;
    this.finlCoords.push([longitude,lattitude])
    }



    this.wapointArray=[];
    // debugger;
    console.log(this.waypoints);
    for(var z = 0 ; z<this.waypoints.length;z++){
      if(this.waypoints[z] != undefined){
        var lat = this.waypoints[z].location.lat();
        var long = this.waypoints[z].location.lng();
      var loc = { location : {
          lat : lat,
          lng : long
        }
      }
        this.wapointArray.push(loc);
      }
  
    }    
    console.log('this.wapointArraythis.wapointArray',this.wapointArray);

    let routeDetail={
      "src":this.sourceRoute,
      "dest":this.destination_route,
      "name":this.rName,
      "user":this.useridd,
      "path":this.finlCoords,
      "poi":this.payloadArray,
      "status":"Active"
    };


      if(this.wapointArray.length>0){
         routeDetail['wayPoints'] = this.wapointArray;
      }
    if((this.speed_alert === true)&&(this.speedAlert != undefined)){
      routeDetail['speed_alert'] = this.speedAlert;
    }
    if(this.deviceArr.length != 0){
      routeDetail['device'] = this.deviceArr;

    }
    console.log(routeDetail);
   
    console.log('this is final payload',routeDetail)
    this.contactService.saveRoute(routeDetail)
      .subscribe(res => {
        this.router.navigateByUrl("vehicleRoute");
      })
  }


}



additionalRouteInfo:any;
saveInfoObject=[];

addField(){
 
  var inputId =  'address' +  this.count++; 
  var t = {
    aid: inputId,
    address:''
  }
  this.fieldArr.push(t);
  
  var temp = setTimeout(()=>{
    this.fieldArr[this.fieldArr.length -1]['address'] = new google.maps.places.Autocomplete(document.getElementById(inputId));
    console.log('this.fieldArr',this.fieldArr);
    clearTimeout(temp);
  },2000)


 
}

deleteAddressField(ind){
  console.log(ind);

    this.fieldArr.splice(ind,1);
    console.log('this.fielArr',this.fieldArr);
    this.getRoute();
}


getClickEvent(i){
  var that = this;
  console.log("inside function");
  console.log(i);
   google.maps.event.addListener(this.fieldArr[i].address, 'place_changed', function() {
        console.log("inside place changed function");
      var latLng =   that.fieldArr[i].address.getPlace().geometry.location;

        that.fieldArr[i]['latLng'] = latLng;
        console.log(that.fieldArr);
  })
}


}


