import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../contact.service';
declare var google: any;
declare var swal: any;
declare var XLSX:any;

@Component({
  selector: 'app-poi-master-edit',
  templateUrl: './poi-master-edit.component.html',
  styleUrls: ['./poi-master-edit.component.scss']
})
export class PoiMasterEditComponent implements OnInit {
  // @ViewChild('select') selectElRef;
  useridd: any;
   uploadJSON: any;
  poiRadius:any=30;
  poitype:any;
  templateIdentifier: boolean;
  editPOItemplate: boolean;
  poiMap: any ;
  poiObject: any;
  poiLat: string;
  poiLong: string;
  POINAME:any;
  emailid: any;
  devicesss: any;
  dev:any;
  poiDevices: any =[];
  latlngArr: any;
  selectedDevices: any;
  Load: boolean;
  POI_ID: any;
  notSelectedPOIArray: any=[];
  untrackedDev: any = [];
  tempArray: any=[];
  uncheckedArr: any=[];
  actionId: any;
  editDiv: boolean;
  failedFiles=[]
  failedUploadFiles:any;
  showErrorupload: boolean;
  faileduploadDevices: any;
  showErrorupload_1: boolean =false;
  source_address: any;
  poiaddress: any;
  addLat: any;
  addlng: any;
  AddMapObj: any;
  addressString: any;
  addressString_edit: string;

  poiType=[
    {view : "Provider",value:""},
     {view : "Customer",value:"customer"},
      {view : "Garage",value:"garage"}, 
      {view : "Emergency",value:"emergency"},
       {view : "Others",value:"others"}, 
       {view : "Gas Station",value:"gas_station"},
       {view :"Residence",value : "residence"},
       {view : "City",value:"city"},
       {view : "Work",value:"work"},
        {view : "Resturant",value:"resturant"}, 
        {view : "Shopping",value:"shopping"},
         {view : "Bank",value:"bank"}, 
         {view : "School",value:"school"},
         {view :"Super Market",value : "supermarket"},
         {view :"Gym",value : "gym"},
         {view : "Home", value : "home"},
         {view :"Grocery Store",value : "grocery_store"}
  ];

  constructor(public dialogRef: MdDialogRef<PoiMasterEditComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,public contactService :ContactService) {
      this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id; 
      this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1]));
      this.poiObject = data;
      console.log(this.poiObject);
      this.actionId = this.poiObject.poiData.actionId ;
      if(this.actionId == "edit"){
        this.templateIdentifier = true;
        console.log(this.templateIdentifier);
        this.POI_ID  = this.poiObject.poiData._id; 
        console.log(this.poiObject);   
        if((this.poiObject.poiData.poi.poi_type != undefined)||(this.poiObject.poiData.poi.poi_type != '')){
          this.poitype = this.poiObject.poiData.poi.poi_type ; 
        }
        this.poiRadius = this.poiObject.poiData ?this.poiObject.poiData.radius :0
        var deviceIDs = this.poiObject.poiData.untrackedDevice?this.poiObject.poiData.untrackedDevice:[];
         console.log(deviceIDs);
        if(deviceIDs.length != 0){
         for(var k =0; k<deviceIDs.length;k++){
           console.log(deviceIDs[k])
           this.untrackedDev.push(deviceIDs[k]);
          }
          console.log("untrackedDevice=>",this.untrackedDev);
        }
         this.notSelectedPOIArray = this.untrackedDev;
      

      }
      if(this.actionId == "add"){
        this.editPOItemplate = true;
      }
      let that = this;
     $("#excelFile").change(function(e){
      let _e:any = e;
      that.failedFiles=[]
      console.log("Inside function");
        var reader = new FileReader();
        console.log(reader);
        reader.onload = function(e) {
         
          let _E:any = e;
          var data = _E.target.result;
       
        
        let workbook = XLSX.read(data, {type: 'binary' });
      
         let first_sheet_name = workbook.SheetNames[0];
      
       let worksheet = workbook.Sheets[first_sheet_name];
       let d:any = XLSX.utils.sheet_to_json(worksheet,{raw:true});
         
       that.uploadJSON=d.map(function(d){  

         if((isFinite(Number(d.lat)) && Math.abs(Number(d.lat)) <= 90)&&(isFinite(d.long) && Math.abs(d.long) <= 180)){
            console.log(d.lat);
            return d;
          }else{
            if(!(that.failedFiles.includes(d))){
                that.failedFiles.push(d)
              }
          }
          
          // else{
          //   // if(that.uploadJSON[i]){
          //     if(!(that.failedFiles.includes(d))){
          //       that.failedFiles.push(d)
          //     }
          //     // that.uploadJSON.splice(i,1)
          //   // }
          // }

          // if(isFinite(d.long) && Math.abs(d.long) <= 180){
          //    console.log(d.long);
          // }else{
          //   // if(that.uploadJSON[i]){
          //     if(!(that.failedFiles.includes(d))){
          //       that.failedFiles.push(d)
          //     }

        

        // return d;
        });
        console.log("file=>",that.uploadJSON);

//         for(var i=0;i<that.uploadJSON.length;i++){
//           // const isLatitude = num => isFinite(num) && Math.abs(num) <= 90;
//           if(isFinite(Number(d.lat)) && Math.abs(Number(d.lat)) <= 90){
//             console.log(d.lat);
            
//           }else{
//             // if(that.uploadJSON[i]){
//               if(!(that.failedFiles.includes(d))){
//                 that.failedFiles.push(d)
//               }
//               // that.uploadJSON.splice(i,1)
//             // }
//           }

//           if(isFinite(d.long) && Math.abs(d.long) <= 180){
//              console.log(d.long);
//           }else{
//             // if(that.uploadJSON[i]){
//               if(!(that.failedFiles.includes(d))){
//                 that.failedFiles.push(d)
//               }
//               // that.uploadJSON.splice(i,1)
//             // }
//           }
//           // const isLatitude =that.uploadJSON[i].lat => isFinite(Number(that.uploadJSON[i].lat)) && Math.abs(Number(that.uploadJSON[i].lat)) <= 90;
// // Longitude must a number between -180 and 180
// // const isLongitude = that.uploadJSON[i].long => isFinite(that.uploadJSON[i].long) && Math.abs(that.uploadJSON[i].long) <= 180;
//         }
        console.log("Failed",that.failedFiles);
        
        that.faileduploadDevices=that.uploadJSON;
        that.showErrorupload_1=true
        };
           reader.readAsBinaryString(_e.target.files[0]); 
      
      });
      
  

     }


  ngOnInit() {
    let outerThis = this;
    if(this.actionId == "edit"){
      var temp  = this.poiObject.poiData.poi.location.coordinates;
      this.poiLat = temp[1];
      this.poiLong = temp[0];
      var current_add = new google.maps.LatLng(this.poiLat, this.poiLong);
      var mapOptions = {
        zoom: 15,
        center: current_add
      };
  
      var map = new google.maps.Map(document.getElementById('poiEditMap'), mapOptions);
      this.poiMap = map;
    
  
      var icon1 = {
        url: "./assets/image/ico_direccion.png", // url
        scaledSize: new google.maps.Size(50, 50), // scaled size
      
    };
      var marker = new google.maps.Marker({
        position: current_add,
        map: map,
        draggable:true,
        icon: icon1
      });
      google.maps.event.addListener(marker, 'dragend', function() 
  {
      console.log("Inside dragend");
  
      outerThis.poiLat = marker.getPosition().lat();
      outerThis.poiLong = marker.getPosition().lng(); 
  });
    }  

    if(this.actionId == "add"){
      this.mapFunction();
      
      
       this.source_address = new google.maps.places.Autocomplete(document.getElementById('txtSource'));
      
    }
    this.getUserDevices();
     
     
  }

  getUserDevices(){
    this.Load = true;
    this.contactService.getDevice(this.emailid.email,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);          
        }   

        if(this.actionId == "edit"){

          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.Load = false;
        this.selectedDevices = this.tempArray;
        }
      },err=>{
        this.Load = false;
        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); 
  }

  savepoi(){
    // deviceArr
    var outerthis = this;
    console.log(this.poiLong,this.poiLat);
    var locationObj = {
      'type' : 'Point',
      "coordinates": [this.poiLong,this.poiLat],
      
    }

    var latlng = {lat: this.poiLat, lng: this.poiLong};
    var geocoder = new google.maps.Geocoder;
    geocoder.geocode({'location': latlng}, function(results, status) {
      if (status === 'OK') {
        if (results[0]) {
        outerthis.addressString_edit = results[0].formatted_address;
        } else {
         console.log('No results found');
         outerthis.addressString_edit = 'Not available';
        }
      } else {
        outerthis.addressString_edit = 'Not available';
        console.log('Geocoder failed due to: ' + status);
      }  
      var editPOIobj = {
        "location": locationObj,
        "poiid" : outerthis.POI_ID,
        "address" : outerthis.addressString_edit,
        "radius" : outerthis.poiRadius
      }
      debugger;
      if(outerthis.poitype != undefined){
        editPOIobj['poi_type'] = outerthis.poitype; 
      }
  
      if(outerthis.notSelectedPOIArray.length != 0){
        editPOIobj['deviceArr'] = outerthis.notSelectedPOIArray;
      }else{
        editPOIobj['deviceArr'] = [];
      }
      console.log(editPOIobj);
      outerthis.Load = true;
      outerthis.contactService.editPOIdetails(editPOIobj)
            .subscribe(res=>{
              outerthis.Load = false;
                console.log(res);
                outerthis.dialogRef.close("success");
            },err=>{
              outerthis.Load = false;
              console.log(err);
            })
    });

  }
  cancel(){
    this.dialogRef.close();
  }

  mapFunction(){
    var that = this;
    console.log("add");
    if (navigator.geolocation) {
      if(location.protocol != 'https:'){
        
        this.contactService.getlatLong().subscribe(res=>{
          console.log(res);
          var position = {
            coords: { 
              latitude: res.lat,
              longitude: res.lon
            }
          };

          that.addLat =  position.coords.latitude;
          that.addlng = position.coords.longitude;

          var curr_position = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          }  

          var mapAdd = new google.maps.Map(document.getElementById('poiAddMap'), {
            center: {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            },
            zoom: 18
        });

        this.AddMapObj = mapAdd;

        
          this.poiFunction(mapAdd,curr_position);
        })
      }
      navigator.geolocation.getCurrentPosition(function(position) {   
        var curr_position = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        }  
        // console.log(this.curr_position);
        that.addLat =  position.coords.latitude;
        that.addlng = position.coords.longitude;
        var mapAdd = new google.maps.Map(document.getElementById('poiAddMap'),{
          center: {lat:  curr_position.lat, lng: curr_position.lng},
          zoom: 15
        });
        that.AddMapObj = mapAdd;
        that.poiFunction(mapAdd,curr_position);


 
      })  
     }
  }

  poiFunction(mapAdd,curr_position){
    var that = this;
    var icon1 = {
      url: "./assets/image/ico_direccion.png", // url
      scaledSize: new google.maps.Size(50, 50), // scaled size
    
  };
    var marker = new google.maps.Marker({
      position: curr_position,
      map: mapAdd,
      draggable:true,
      icon: icon1
    });

    google.maps.event.addListener(marker, 'dragend', function() 
    {
        console.log("Inside dragend");
    
         var la = marker.getPosition().lat();
         var ln = marker.getPosition().lng(); 
         that.addLat =la;
         that.addlng = ln;

         console.log(that.addLat,that.addlng);
     
    });


    var input = document.getElementById('txtSource');
            var searchBox = new google.maps.places.SearchBox(input);
          
            searchBox.addListener('places_changed', function() {
              var places = searchBox.getPlaces();
              if (places.length == 0) {
                return;
              }
              console.log(places);
    
              var bounds = new google.maps.LatLngBounds();
              places.forEach(function(place:any) {
                console.log('place.formatted_address',place.formatted_address);
                console.log(place.geometry.location);
                that.addressString = place.formatted_address;
                that.addLat =  place.geometry.location.lat();
                that.addlng = place.geometry.location.lng();
                console.log(that.addLat,that.addlng);


                if (!place.geometry) {
                  // console.log("Returned place contains no geometry");
                  return;
                }
                var icon = {
                  url: icon1,
                  size: new google.maps.Size(50, 50),
              
                };

    
                if (place.geometry.viewport) {
                  // Only geocodes have viewport.
                  
                  bounds.union(place.geometry.viewport);
                } else {
                  bounds.extend(place.geometry.location);
                }
                marker.setPosition(place.geometry.location);
                marker.setVisible(true);
              });
              mapAdd.fitBounds(bounds);
            });
    
  }


  test(){

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


  addPOI(){
    var that = this;
    console.log(this.addLat,this.addlng);
    console.log(this.addressString);
    if(!this.addressString){
      console.log(this.addLat,this.addlng);
      var latlng = {lat: this.addLat, lng: this.addlng};
      var geocoder = new google.maps.Geocoder;
      geocoder.geocode({'location': latlng}, function(results, status) {
        if (status === 'OK') {
          if (results[0]) {
          that.addressString = results[0].formatted_address;
          } else {
           console.log('No results found');
           that.addressString = 'Not available';
          }
        } else {
          that.addressString = 'Not available';
          console.log('Geocoder failed due to: ' + status);
        }
        var locationObj = {
          'type' : 'Point',
          "coordinates": [that.addlng,that.addLat]
        }
         
        var poiObj = {
          poi:  [
            {  
              "location": locationObj,
              "poiname" : that.POINAME,       
              "status": "Active",
              "user" : that.useridd,
              "address" : that.addressString,
              "radius" : that.poiRadius
            }
          ]
        }

        if(this.poitype != undefined){
          poiObj.poi[0]['poi_type'] = this.poitype
        }
        that.savePOI(poiObj);

      });
    }else{
      var locationObj = {
        'type' : 'Point',
        "coordinates": [this.addlng,this.addLat]
      }
       
      var poiObj = {
        poi:  [
          {  
            "location": locationObj,
            "poiname" : this.POINAME,       
            "status": "Active",
            "user" : this.useridd,
            "address" : this.addressString,
            "radius" : this.poiRadius
          }
        ]
      }

      if(this.poitype != undefined){
        poiObj.poi[0]['poi_type'] = this.poitype ; 
      }
      this.savePOI(poiObj)
    }
  }

  savePOI(poiObj){
    this.Load =true;
    console.log(poiObj);
    this.contactService.addOnePoi(poiObj)
    .subscribe(res=>{
      this.Load= false;
      this.dialogRef.close("success");
    },err=>{
      this.Load= false;
      swal(
        'Server Error',
        'Error occured while adding POI , Please try after sometime !!!',
        'error'
      )  
    })
  }

  getpoi_type(type){
    console.log('type',type);
    this.poitype = type;
  }
}


