import { Component, OnInit } from '@angular/core';
import { Params, Router, ActivatedRoute } from '@angular/router'
import { ContactService } from '../contact.service';
import { PoiListComponent } from '../poi-list/poi-list.component';
import { PoiDtlDelComponent } from "../poi-dtl-del/poi-dtl-del.component";
import { MdDialog } from '@angular/material';
import { Data } from '../data';

declare var google: any;
@Component({
  selector: 'app-show-route',
  templateUrl: './show-route.component.html',
  styleUrls: ['./show-route.component.scss']
})
export class ShowRouteComponent implements OnInit {
  marker1: any;
  data_descip:any;
  mapData: any[];
  routePath: any;
  before: any;
  logoutbut: boolean;
  cust: boolean = false;
  routename:any;
  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;
  deviceId: any;
  routeSource:any;
  routeDest:any;
  device_update: any;
  markerpoi: any;
  superAdmin: any = false;
  waypoints_path:any;
  routeData:any;
  cnt:any =0;
  dbMap:any;
  dbMapInit:any = false;
  speed_alert: boolean = true;
  rName: any;
  sourceRoute: any;
  destination_route: any;
  curr_position: any;
  directionsService: any;
  directionsDisplay: any;
  speedAlert:any;
  wayPoinrArr: any;
  variableId: string;
  waypoint1: any={};
  waypoints: any;
  wapointArray: any[];
  finlCoords: any;
  show:Boolean=false;
  underscore_id: any;
  constructor(private router: Router, private route: ActivatedRoute, private contactService: ContactService,public dialog: MdDialog) {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    var routeID = localStorage.getItem('routeId'); 
    this.getRouteData(routeID);
    // });
  }

  ngOnInit() {
    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'] = 'Tthis.rue'
    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.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
    // this.routePath = JSON.parse(localStorage.getItem('routeData'));
    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.showRoute()
    localStorage.removeItem('mapLoad_ID')
    // this.router.navigateByUrl("add");
    this.routeSource = new google.maps.places.Autocomplete(document.getElementById('txtSource'));

    this.routeDest =  new google.maps.places.Autocomplete(document.getElementById('txtDestination'));

//     google.maps.event.addListener(this.routeSource , 'place_changed', function() {
    

    
// })


    // this.initialize()




  }




  getRouteData(id) {
    var i = id;
    this.underscore_id = id;
    var outerThis = this;

    var u = this.useridd
    this.contactService.getPOIdata(i, u)
      .subscribe(res => {
        var rPath = res;
        this.rName = rPath.routeName;
        console.log('rPathrPathrPathrPathrPathrPath',rPath);
       
        this.routeSource = rPath.source;
        this.routeDest = rPath.destination
       
        this.speedAlert = rPath.speed_alert;
       
     
        //console.log(rPath.waypoints);
        this.routeData = res;
        this.showRoute(res);
        this.variableId =''
        var t = {
          aid: '', 
          address:'',
          astring:'',
          place_changed: false,
          latLng : {lat:0,lng:0}
        
        }
     
      //  console.log('this.routeData',this.routeData);
         var that = this;
         console.log(rPath.destination);
         if((rPath.waypoints != undefined)&&(rPath.waypoints.length != 0)){
           var j=0;    
          for (var i = 0; i < rPath.waypoints.length; i++) {
           
              var inputid = 'address' +  this.count++;  
           
              t = {
                aid: inputid, 
                address:'',
                astring:'',
                place_changed: false,
                latLng : {lat: rPath.waypoints[i].location.lat,lng: rPath.waypoints[i].location.lng}         
              }
              this.fieldArr.push(t);
            
            
              
            that.clocation_1(rPath.waypoints[i].location, function (err, succ) {
              
                  that.fieldArr[j]['astring'] = succ.endAddress; 
              
              // }         
              if (err) {
             
                j++;
              } else {
            
                j++;
                if (j === rPath.waypoints.length) {
                  console.log(that.fieldArr);
                  that.attachAutocomplete()
                return
                }
              }
            })  
          }
         }else{
          that.loadMap();
          // var vtp = setTimeout(()=>{
          //   that.routeDest=new google.maps.places.Autocomplete(document.getElementById(that.variableId));  
          //   that.routeDest = rPath.destination;
          //   var attachdata = document.getElementById(that.variableId);    
          //   attachdata.setAttribute("value", that.routeDest);
          
          //   clearTimeout(vtp);
          // })
        
         }

         console.log(this.fieldArr);  
    
   
      })
  }

  testShit='';

  attachAutocomplete(){
    var that= this;
    console.log(this.fieldArr);
    for(var p = 0; p<this.fieldArr.length;p++){
        console.log(this.fieldArr[0].aid);
        var attachdata = document.getElementById(this.fieldArr[p].aid);   
        this.fieldArr[p]['address']=new google.maps.places.Autocomplete(document.getElementById(this.fieldArr[p].aid)); 
        attachdata.setAttribute("value", this.fieldArr[p]['astring']);  
    }
    // var tita= document.getElementById(this.variableId);
    //   this.waypoint1['aid']= this.variableId;
    //   this.waypoint1['address']= new google.maps.places.Autocomplete(tita);
    //   this.waypoint1['astring']= this.routeDest;
    //   this.waypoint1['place_changed']= true;



      //  tita.setAttribute("value", this.routeDest)
       this.loadMap();

  }


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


 

  dataArrayCoords: any;
  currentLatitude: any;
  currentLongitude: any;
  marker: any;
  showRoute(rP) {
    var outerThis = this;

    this.routePath = rP;


    this.mapData = [];
    for (var i = 0; i < this.routePath.routePath.length; i++) {
      this.mapData.push({
        "lat": this.routePath.routePath[i].location.coordinates[1],
        "lng": this.routePath.routePath[i].location.coordinates[0]
      });
    }
      this.curr_position={
        lat :this.routePath.routePath[0].location.coordinates[1],
        lng: this.routePath.routePath[0].location.coordinates[0]
      }
 


    if(this.dbMapInit == false){
      var current_add = new google.maps.LatLng(18.6018583, 73.77622640000004);
      var mapOptions = {
        zoom: 10,
        center: current_add
      };
      if(this.dbMap != undefined && this.dbMap.mapTypeId != undefined){
     
        current_add = new google.maps.LatLng(this.dbMap.center.lat(),this.dbMap.center.lng());
        mapOptions = {
          zoom: this.dbMap.zoom,
          center: current_add
        };
      }

      var map = new google.maps.Map(document.getElementById('showMap'), mapOptions);
      this.dbMap = map;
      this.dbMapInit = true;
    }else{
      map = this.dbMap;
    }




    var pinImage = new google.maps.MarkerImage("http://www.googlemapsmarkers.com/v1/S/009900/");
    this.marker = new google.maps.Marker({
      position: this.mapData[0],
      map: map,
      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: map,
      icon: pinImage1
    });

    for (var i = 0; i < this.routePath.poi.length; i++) {
      let test = this.routePath.poi[i];
      var poiMarker_object = {
        "lat": this.routePath.poi[i].poi.location.coordinates[1],
        "lng": this.routePath.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: map,
        icon: pinImagePOI
      });

      // outerThis.attachSecretMessage(this.markerpoi,this.routePath.poi[i].poi.poiname);
      google.maps.event.addListener(this.markerpoi, 'click',function(event){
        // //console.log(event,test);
        // outerThis.shownDelete(test);
        
      });
    }

    this.wayPoinrArr=[];

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

        infowindow.setContent(outerThis.routePath.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 () {

        infowindow.setContent(outerThis.routePath.destination);
        infowindow.open(this.map, outerThis.marker1);
      }
    })
      (this.marker1)
    );


    var flightPath = new google.maps.Polyline({
      path: this.mapData,
      geodesic: true,
      strokeColor: '#1E90FF',
      strokeOpacity: 1.0,
      strokeWeight: 6
    });
    let that = this;
  google.maps.event.addListener(flightPath, 'click', function(h) {

    that.waypoints_path = 
    {
      "coordinates": [
        h.latLng.lng(),
        h.latLng.lat()
      ],
      "type": "Point"
    };
    // that.addInfo();
  });

    flightPath.setMap(map);
    zoomToObject(flightPath);

    function zoomToObject(obj){
      var bounds = new google.maps.LatLngBounds();
      var points = obj.getPath().getArray();
      for (var n = 0; n < points.length ; n++){
          bounds.extend(points[n]);
      }
      map.fitBounds(bounds);
  }

  }
  additionalRouteInfo:any;
  saveInfoObject=[];

  // dbshow(data){

  //   let sendData =     {
  //     "poi": [
  //       {
  //         "location": data.poi[0].location,
  //         "poiname": data.poi[0].pname,
  //         "duration_from_previous":data.poi[0].prv_dur,
  //         "duration_to_next": data.poi[0].nxt_dur,
  //         "duration_halt":  data.poi[0].dur_halt,
  //         "trackroute": data.trackroute,
  //         "status": "Active",
  //         "user": data.user,
  //         "routeIndex":this.cnt
  //       }
  //     ],

  //   };
  //  this.contactService.addOnePoi(sendData).subscribe(resp=>{
  //   this.getRouteData(localStorage.getItem('routeId'));
  //   this.cnt +=1;
  //       })
  // }
//   addInfo(){
//     let dialogRef_1 = this.dialog.open(PoiListComponent, {
//       height:'294px',
//       width:'500px',  
//     });
//   let that = this;
//     dialogRef_1.afterClosed().subscribe(result => {
//       if(result){
//         let sendData = JSON.parse(result);
//         sendData.location  =  that.waypoints_path;
//       that.dbshow({poi:[sendData],trackroute:localStorage.getItem('routeId'),status:'Active',user:that.useridd});


//       }else{
//         this.additionalRouteInfo={
//           "pname":'',
//           "prv_dur" : '',
//           "nxt_dur": '',
//           "dur_halt" : ''
//         };
//         this.saveInfoObject.push(this.additionalRouteInfo);
//       }
//     })


// }

// shownDelete(data){
  
//   localStorage.poiShowDelData = JSON.stringify(data);
//   let dialogRef_1 = this.dialog.open(PoiDtlDelComponent, {
//     height:'294px',
//     width:'500px',  
//   });
//   let that = this;
//   dialogRef_1.afterClosed().subscribe(result => {
//     if(result == 'delete'){
//       that.getRouteData(localStorage.getItem('routeId'));
//       that.dbMapInit = false;
//     }
        
//     });
// }


loadMap(){
  if(this.dbMapInit == false){
    var current_add = new google.maps.LatLng(18.6018583, 73.77622640000004);
    var mapOptions = {
      zoom: 10,
      center: current_add
    };
    if(this.dbMap != undefined && this.dbMap.mapTypeId != undefined){
   
      current_add = new google.maps.LatLng(this.dbMap.center.lat(),this.dbMap.center.lng());
      mapOptions = {
        zoom: this.dbMap.zoom,
        center: current_add
      };
    }

    var map = new google.maps.Map(document.getElementById('showMap'), mapOptions);
    this.dbMap = map;
    this.dbMapInit = true;
  }else{
    map = this.dbMap;
  }
var map = this.dbMap;

    // var pp = setTimeout(()=>{             
    //       this.getRoute();
    //       clearTimeout(pp);
    //     },1000)

}


getRoute(){

  var outerThis=this;
  var sr  = document.getElementById('txtSource');
  this.sourceRoute=sr['value'];
  var ds = document.getElementById('txtDestination');
 
  this.waypoints=[];
  // console.log(this.fieldArr);
  
  if(this.fieldArr.length >0){
        for(var k = 0; k<this.fieldArr.length ;k++){   
          if(this.fieldArr[k].latLng!=undefined){
            if(this.fieldArr[k].place_changed === false){
              var la =  new google.maps.LatLng(this.fieldArr[k].latLng.lat,this.fieldArr[k].latLng.lng);
            }else{
              var la =  new google.maps.LatLng(this.fieldArr[k].latLng.lat(),this.fieldArr[k].latLng.lng());
            }
            var pp = {
              location : la,
              stopover:false
            }
            outerThis.waypoints.push(pp);  
          }
        }
        console.log('outerThis.waypoints',outerThis.waypoints);

  }

  if(this.fieldArr.length=== 0 ){
    outerThis.waypoints =[];
  }

  console.log(ds);
  this.destination_route = ds['value'];
  console.log('this.destination_route',this.destination_route);
  if(outerThis.directionsDisplay != undefined) { 
    outerThis.directionsDisplay.setMap(null);
    outerThis.directionsDisplay = null;
   }


outerThis.directionsService = new google.maps.DirectionsService;
outerThis.directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: this.dbMap, 
  });
  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, outerThis.directionsService,outerThis.directionsDisplay,this.dbMap,outerThis.waypoints)

 }

 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';
}
path=[];
overview_path_latlng=[];
displayRoute(origin, destination, service, display,map,waypts) {
  //console.log(origin ,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();
         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=[];
  
         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);
         }
        
         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("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);
      }
    });
  
  }

updateRoute(){
  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{

    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,  
      "status":"Active",
      "_id":this.underscore_id
     
    };


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

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

}
changeDetactor(ev){
  this.speed_alert = ev.checked;

}
fieldArr=[];
count=0;

addField(){
 
  var inputId =  'address' +  this.count++; 
  var t = {
    aid: inputId,
    address:'',
    astring:'',
    place_changed:false

  }
  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){
    this.fieldArr.splice(ind,1);
    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;
        that.fieldArr[i]['place_changed'] = true;
      
        //console.log(that.fieldArr);
  })
}



clocation_1(latlngObj, cb) {
  var outerThis = this;
  var la = '';

  let latLng = {
    lat: "0",
    long: "0"
  };
  if (latlngObj) {
    latLng = {
      lat: latlngObj.lat ? latlngObj.lat : 0,
      long: latlngObj.lng ? latlngObj.lng : 0
    }
  }

  outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
    if (res.message == "Address not found in databse") {
      latlngObj['startAddress'] = "NA";
      cb(null, latlngObj);
        } else {
          latlngObj['endAddress'] = res.address;
          cb(null, latlngObj);
        }

      })

      // cb(null,latlngObj);
    }

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


      initialize() {
        // this.show=true
      const myOptions = {
        zoom:2,
        center: new google.maps.LatLng(18.602941, 73.777147),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      
     var map = new google.maps.Map(document.getElementById('showMap'), myOptions);
      console.log('mapmapmapmapmapmapmapmapmapmapmapmapmapmap',map);
      // outerThis.historyMap = map;
      var trafficLayer = new google.maps.TrafficLayer();
      trafficLayer.setMap(map);
     
      // var isMapInit = true;

      var zoomBar: any;
      zoomBar = document.getElementById('myRange');
      map.setZoom(map.getZoom());

    
      zoomBar.value = map.getZoom();
  
      zoomBar.oninput = function () {
        //console.log('zoomValue',map.getZoom());
        map.setZoom(parseInt(this.value));
      }

      google.maps.event.addListener(map, 'zoom_changed', function (event) {
        //console.log("Inside zoom in out function");
        if (zoomBar.value)
          zoomBar.value = map.getZoom();
      });

       

    }



  


}


