
import { Component, OnInit } from '@angular/core';
import { Params, Router, ActivatedRoute } from '@angular/router'
import { ContactService } from '../contact.service';

import { MdDialog, MdDialogRef } from '@angular/material';
declare var XLSX:any;


declare var google: any;
@Component({
  selector: 'app-poi-menu',
  templateUrl: './poi-menu.component.html',
  styleUrls: ['./poi-menu.component.scss']
})
export class PoiMenuComponent implements OnInit {
uploadJSON: any;
  tollList;
  failedFiles=[]
  failedUploadFiles:any;
  showErrorupload: boolean;
  faileduploadDevices: any;
  showErrorupload_1: boolean =false;
  useridd: any;
  constructor(private router: Router, private route: ActivatedRoute,public dialogRef: MdDialogRef<PoiMenuComponent>, private contactService: ContactService,public dialog: MdDialog) {

  }

  ngOnInit() {
     this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
     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},{skipHeader:true});
         
       that.uploadJSON=d.map(function(d){  
         console.log(d);
         if(!d.Altitude){
          return false;
         }
          if(!d.Longitude){
          return false;
         }
          if(!d.Address){
          return false;
         }
          if(!d['Client Name']){
          return false;
         }
          var lat = d.Altitude.split(/[^\d\w\.]+/);
          var long = d.Longitude.split(/[^\d\w\.]+/);
          console.log(lat,'LONG=',long);
          if(lat[0]&&lat[1]&&lat[2]&&lat[3]){
            d.location=[long[0],lat[0]]
            d.latitude=that.ConvertDMSToDD(lat[0],lat[1],lat[2],lat[3])
          }else{
            d.latitude=long[0]

          }
           if(long[0]&&long[1]&&long[2]&&long[3]){
            // d.location=[long[0],lat[0]]
            d.longitude=that.ConvertDMSToDD(long[0],long[1],long[2],long[3])
          }else{
            d.longitude=lat[0]

          }
          
        //  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)
          //     }
          // }
          
        });
        console.log("file=>",that.uploadJSON);


        console.log("Failed",that.failedFiles);
        
        that.faileduploadDevices=that.uploadJSON;
        that.showErrorupload_1=true
        };
           reader.readAsBinaryString(_e.target.files[0]); 
      
      });

  }
  uploadExcel(){
    var arr=[]
    for(var i=0;i<this.uploadJSON.length;i++){
      if(this.uploadJSON[i]){
        arr.push({
          location:{type:"Point",
          coordinates:[Number(this.uploadJSON[i].longitude),Number(this.uploadJSON[i].latitude)]},
        poiname:this.uploadJSON[i]['Client Name'],
        poi_type:'Hospital',
        address:this.uploadJSON[i].Address,
        radius:60,
        user:this.useridd,
        })

      }
    }
    console.log(arr);
    
    this.contactService.post('/poi/addMultiple',{data:arr}).subscribe((res:any)=>{
      console.log(res);
       this.dialogRef.close("success"); 
    })
  }

  
ParseDMS(input) {
    var parts = input.split(/[^\d\w\.]+/);    
    var lat = this.ConvertDMSToDD(parts[0], parts[2], parts[3], parts[4]);
    var lng = this.ConvertDMSToDD(parts[5], parts[7], parts[8], parts[9]);

    return {
        Latitude : lat,
        Longitude: lng,
        Position : lat + ',' + lng
    }
}
ConvertDMSToDD(degrees, minutes, seconds, direction) {  
  console.log(degrees, minutes, seconds, direction);
   
    var dd = Number(degrees) + Number(minutes)/60 + Number(seconds)/(60*60);

    if (direction == "S" || direction == "W") {
        dd = dd * -1;
    } // Don't do anything for N or E
    return dd;
}

}