import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { MdDialog } from '@angular/material';
import { Router } from '@angular/router';
import { ContactService } from '../contact.service';
declare var google: any;
declare var $:any;
@Component({
  selector: 'app-route-plan',
  templateUrl: './route-plan.component.html',
  styleUrls: ['./route-plan.component.scss']
})
export class RoutePlanComponent implements OnInit {
superAdmin: any;
  speed_alert:boolean=true;
  speedAlert:any;
  destination_route: any;
  sourceRoute: any;
  before:any;
  fieldArr=[];
  poiArray=[]
  startPoint;
  disabled:boolean=true;
  endPoint;
  haultArray=[];
  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;
   countForRid=0;
   countForHid=0;
  directionsDisplay: any;
  ll: { location: any; stopover: boolean; };
  wapointArray: any[];
   routePlanForm: FormGroup;
  haultFormArray: FormArray;
  constructor(private fb: FormBuilder,private router: Router,private contactService: ContactService,public dialog: MdDialog) {
      }

    createItem() {
    return this.fb.group({
      name: [''],
    })
  }

   addItem() {
    this.haultFormArray = this.routePlanForm.get('haultFormArray') as FormArray;
    this.haultFormArray.push(this.createItem());

    console.log(this.routePlanForm.value);
     var inputId =  'address' +  this.count++; 
  var t = {
    aid: inputId,
    address:''
  }
   this.fieldArr.push(t);
   console.log(this.fieldArr);
   
  }
vehicle
  ngOnInit() {

    var data1= JSON.parse(localStorage.getItem('routePlanData'));
    console.log(data1);
    

     var inputId =  'address' +  this.count++; 
  var t = {
    aid: inputId,
    address:''
  }
this.fieldArr.push(t);
     this.routePlanForm = this.fb.group({
      haultFormArray: this.fb.array([this.createItem()]),
      startPoint:[''],
      endPoint:[''],
      name:[''],
      vehicle:['']
    })

    

    

    this.loadropdown();
    
    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. getPoiList()
  this.initMap();
      if(data1!=undefined){
      this.routePlanForm.patchValue({
      haultFormArray: data1.hault,
      startPoint:data1.startPoint._id,
      endPoint:data1.endPoint._id,
      name:data1.name,
      vehicle:data1.vehicle._id
      })

     localStorage.removeItem('routePlanData')
    }
  }
  mainPoiArray=[]
  getPoiList(){
    this.contactService.get('/poi/getPois?user='+this.useridd).subscribe((res:any)=>{
      // this.poiArray=res;
      this.mainPoiArray=res;
      var poiObj; 

    for(var i=0;i<res.length;i++){
      poiObj ={
          poiname: res[i].poi.poiname,
          id : res[i]._id,
          location:res[i].poi.location.coordinates,
          address:res[i].poi.address
        }

        this.poiArray.push(poiObj);
        if(this.poiArray.length==res.length){
          this.loadropdown();

        }
    }
    })
  }


  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(() => {
      $('#vehicles').multipleSelect({
        width: 200,
        placeholder: 'Select Vehicle',
        filter: true,
        single: true,
        selectAll: false
 
      })
  
   
    }, 100);

    // $("vehicles").find("option[value="+this.routePlanForm.value.vehicle+"]").prop("selected", "selected");

// setTimeout(() => {
//      $('#startPoint').multipleSelect({
//         width: 200,
//         placeholder: 'Select Start Point',
//         filter: true,
//         single: true,
//           selectAll: false
 
//       })
  
   
//     }, 100);

    //  setTimeout(() => {
    //     $('#hault').multipleSelect({
    //       width: 200,
    //       placeholder: "Select Hault",
    //       filter: true,
    //       single: true,
    //       selectAll: false  
    //     }) 
    //   }, 150);

    //   setTimeout(() => {
    //     $('#endPoint').multipleSelect({
    //       width: 200,
    //       placeholder: "Select endpoint",
    //       filter: true,
    //       single: true,
    //       selectAll: false  
    //     }) 
    //   }, 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');

  console.log('this.fieldArr',this.fieldArr.length,this.fieldArr,this.ll);
  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++){
         
          console.log(this.fieldArr[k].latLng[1],this.fieldArr[k].latLng[0]);
          
       
          if(this.fieldArr[k].latLng!=undefined){
            var pp = {
              location : new google.maps.LatLng(this.fieldArr[k].latLng[1],this.fieldArr[k].latLng[0]),
              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.startAddress, this.endAddress, directionsService,outerThis.directionsDisplay,map,this.waypoints)
  this.disabled=false;
 }

 

  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;
  console.log(total);
  
  // 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(){

  console.log(this.routePlanForm.value,$('#vehicles').multipleSelect('getSelects','value'));
  var vehicle=$('#vehicles').multipleSelect('getSelects','value');

  var selectedVehicle
  console.log(vehicle[0]);
 var  hault=[]
for (let i=0;i<this.routePlanForm.value.haultFormArray.length;i++) {
   hault.push(this.routePlanForm.value.haultFormArray[i].name)
}
  
var t=vehicle[0].substr(vehicle[0].indexOf(' ')+1)
console.log(selectedVehicle,vehicle[0].substr(vehicle[0].indexOf(' ')+1), this.RemoveDoubleQuotes(t));
     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])
    }
  
  //  console.log(t);
   var data={
     name:this.routePlanForm.value.name,
     vehicle: this.RemoveDoubleQuotes(t),
     startPoint:this.routePlanForm.value.startPoint,
     endPoint:this.routePlanForm.value.endPoint,
     hault:hault,
     user:this.useridd,
      "waypoints":this.finlCoords,
   }
   console.log(data);

   this.contactService.post('/RoutePlan/add',data).subscribe(res=>{
     console.log(res);
     this.router.navigate(['/routePlan'])
     
   })
   
  // 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={
  //     "startPoint":this.sourceRoute,
  //     "endPoint":this.destination_route,
  //     "name":this.rName,
  //     "user":this.useridd,
  //     "waypoints":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");
  //     })
  // }


}

 RemoveDoubleQuotes(str) {
  var firstChar = str.charAt(0);
  var lastChar = str[str.length -1];
  //double quotes
  if(firstChar && lastChar === String.fromCharCode(34)){
    str = str.slice(1, -1);
  }
  //single quotes
  if(firstChar && lastChar === String.fromCharCode(39)){
    str = str.slice(1, -1);
  }
  return str;
}



additionalRouteInfo:any;
saveInfoObject=[];

addField(){
 
  var inputId =  'address' +  this.count++; 
  var radiusId='radius' +  this.countForRid++;
  var haultId='hault' +  this.countForHid++;
  var t = {
    aid: inputId,
    rid:radiusId,
    hid:haultId,
    address:'',
    radius:'',
    haultTime:''

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


 
}

deleteAddressField(i){

      // this..pop();
      this.haultFormArray.removeAt(i);
  // console.log(ind);

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


getClickEvent(i){
  console.log(i);
  
  var that = this;
  console.log("inside function",i);
  for(var j=0;j<this.poiArray.length;j++){
      console.log(this.routePlanForm.value.name[i],'==',this.poiArray[j]);

      // 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;
    
      console.log(this.fieldArr);
           this.fieldArr[i]['latLng'] = this.poiArray[j].location
           console.log(this.fieldArr);
    //  })
  }
  // console.log(i);

}

startAddress;
endAddress;
selectPoint(type){
  console.log(type,type=='startPoint',typeof(type),this.poiArray.length);
  
  const that=this
  if(type=='startPoint'){
    console.log('in');
    for(var i=0;i<this.poiArray.length;i++){
      // console.log(this.routePlanForm.value.startPoint,'==',this.poiArray[i]);
      
      if(this.routePlanForm.value.startPoint==this.poiArray[i].id){

        this.startAddress=this.poiArray[i].address
        this.ll ={
      location : new google.maps.LatLng(this.poiArray[i].location[1],this.poiArray[i].location[0]),
      stopover:false
    }
      //    google.maps.event.addListener(this.poiArray[i].address,  function() {
      //   console.log("inside place changed function");
      // var latLng =   that.fieldArr[i].address.getPlace().geometry.location;
        // that.fieldArr[i]['address'] = this.poiArray[i].address;
        // that.fieldArr[i]['latLng'] = this.poiArray[i].location;
        console.log(that.fieldArr);
  // })

        // this.getGoogleAddress(this.poiArray[i].location[1],this.poiArray[i].location[0],function (err, succ) {
        //   // var that=this;
        //    if(err){
        //     console.log(err)
        //   }if(succ){
        //   console.log(succ);
          
        //   that.startAddress=succ
        //   console.log(that.startAddress);
        //   }
        // })
        
      }
    }
  }else{
     for(var i=0;i<this.poiArray.length;i++){
      console.log(this.routePlanForm.value.endPoint,'==',this.poiArray[i]);
      
      if(this.routePlanForm.value.endPoint==this.poiArray[i].id){
         this.endAddress=this.poiArray[i].address
      //    google.maps.event.addListener(this.poiArray[i].address, 'place_changed', function() {
      //   console.log("inside place changed function");
      // var latLng =   that.fieldArr[i].address.getPlace().geometry.location;
        //  that.fieldArr[i]['address'] = this.poiArray[i].address;
        this.ll ={
      location : new google.maps.LatLng(this.poiArray[i].location[1],this.poiArray[i].location[0]),
      stopover:false
    }
        // that.fieldArr[i]['latLng'] = this.poiArray[i].location;
        console.log(that.fieldArr);
  // })



        // this.getGoogleAddress(this.poiArray[i].location[1],this.poiArray[i].location[0],function (err, succ) {
        //   // var that=this
        //   if(err){
        //     console.log(err)
        //   }if(succ){
            
        //     that.endAddress=succ
        //     console.log(that.endAddress,succ);
        //   }

        // })
        
      }
    }
  }
  // console.log(event);
  // var start=$('#dbselectIMEI').multipleSelect('getSelects','value');
  console.log(this.routePlanForm.value.startPoint);
  
}

getGoogleAddress(lat,long,cb){
  let geocoder = new google.maps.Geocoder();
               let t_latlng=new google.maps.LatLng(lat,long)
                let request = {
                  latLng: t_latlng
                };
                geocoder.geocode(request, function (data, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    if (data[0] != null) {
                      console.log(data,data[0].formatted_address);
                      
                      var liveAdd = data[0].formatted_address;
                     cb(null,data[0].formatted_address);
                    } 
                  }
                  else {
  
                   cb(null,'')
                   
                  }
  
                })
}



}


