import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FlashMessagesService } from 'angular2-flash-messages';
import { ContactService } from '../contact.service';
declare var XLSX:any;

@Component({
  selector: 'app-toll',
  templateUrl: './toll.component.html',
  styleUrls: ['./toll.component.scss']
})
export class TollComponent implements OnInit {
  uploadJSON: any;
  tollList;
  failedFiles=[]
  failedUploadFiles:any;
  showErrorupload: boolean;
  faileduploadDevices: any;
  showErrorupload_1: boolean =false;
  Load: boolean;
  tollForm:FormGroup
  data_descip: string;
  buttonStatus=false
  id
  constructor(private contactService:ContactService,private fb:FormBuilder,private _flashMessagesService: FlashMessagesService) { }

  ngOnInit() {
    this.getTollsList()
    this.tollForm=this.fb.group({
      tollName:['',Validators.required],
        latitude:['',Validators.required],
        longitude:['',Validators.required],
        tollTax:['',Validators.required],
        status:['',Validators.required],
        address:['',Validators.required],
    })
     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]); 
      
      });
  }

  isControlHasError(controlName: string, validationType: string): boolean {
		const control = this.tollForm.controls[controlName];
		if (!control) {
			return false;
		}

		const result =
			control.hasError(validationType) &&
			(control.dirty || control.touched);
		return result;
	}

  uploadExcel(){
    this.failedUploadFiles = [];
    for(var i=0;i<this.uploadJSON.length;i++){
      
      var location={
        type:"Point",
        coordinates:[this.uploadJSON[i].long,this.uploadJSON[i].lat]
      }
      this.uploadJSON[i].location=location;
      this.uploadJSON[i].tollTax=Number(this.uploadJSON[i].tollTax)
      // this.uploadJSON[i].location.coordinates.push(Number(locations[0]))
      // this.uploadJSON[i].location.coordinates.push(Number(locations[1]))
    }
    // this.Load =true;
    console.log("Device Json Payload",this.uploadJSON);
    var data={
      data:this.uploadJSON
    }
    this.contactService.addMultipleTolls(data).subscribe(res=>{
      console.log(res);
      this.getTollsList()
      this.tost1('')
    })
  
 }
submit(){
  const controls = this.tollForm.controls;
		/** check form */
		if (this.tollForm.invalid) {
			Object.keys(controls).forEach(controlName =>
				controls[controlName].markAsTouched()
			);
			return;
		}
  console.log(this.tollForm.value);

  var data={
    tollName:this.tollForm.value.tollName,
        location:{
         type:"Point",
        coordinates:[this.tollForm.value.latitude,this.tollForm.value.longitude]
        },
        tollTax:this.tollForm.value.tollTax,
        status:this.tollForm.value.status,
        address:this.tollForm.value.address,
  }
  if(this.buttonStatus){
    data['id']=this.id;
    console.log(data);
    this.contactService.updateToll(data).subscribe(res=>{
      console.log(res);
      this.tollForm.reset();
      this.tost1('update');
      this.getTollsList()
    })

  }else{
    console.log(data);
    this.contactService.addToll(data).subscribe(res=>{
      console.log(res);
      this.tollForm.reset();
      this.tost1('single');
      this.getTollsList()
      
    })

  }
  
  
}

getTollsList(){
  this.contactService.getTolls().subscribe(res=>{
    console.log(res);
    this.tollList=res
  })

}

 tost1(divid){
  if(divid == "single"){
     this.data_descip = "Toll Added Successfully"
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-success', timeout: 3000 });
   }else if(divid=="delete"){
      this.data_descip = "Record Deleted Successfully"
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-success', timeout: 3000 });
   }
   else if(divid=="update"){
      this.data_descip = "Record Updated Successfully"
     this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-success', timeout: 3000 });
   }
  
   else{
    this.data_descip =  "Tolls Added Successfully"
    this._flashMessagesService.show(this.data_descip, { cssClass: 'alert-success', timeout: 3000 });
   }
  //    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", ""); }, 450000);
  //  }
    }

    deleteToll(data){
      this.contactService.deleteToll({id:data._id}).subscribe(res=>{
        this.getTollsList();
        this.tost1("delete")
      })

    }
    edit(data){
      this.id=data._id
      this.tollForm.patchValue({
         tollName:data.tollName,
        latitude:data.location.coordinates[0],
        longitude:data.location.coordinates[1],
        tollTax:data.tollTax,
        status:data.status,
        address:data.address,
      })
      this.buttonStatus=true
    }

    AddButton(){
      this.buttonStatus=false;
      this.tollForm.reset()
    }
}
