import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { router } from '../../app.router';
import { ContactService } from '../../contact.service';
import { ReportService } from '../../report/report.service';
declare var google: any;

@Component({
  selector: 'app-add-job-card',
  templateUrl: './add-job-card.component.html',
  styleUrls: ['./add-job-card.component.scss']
})
export class AddJobCardComponent implements OnInit {
  source_address: any;
  jobType=['New Installation','Service','Sim Change','Device with Fuel/Tempreture Sensor']
//   [6:28 PM, 8/30/2021] Job 1: New Installation
// [6:28 PM, 8/30/2021] Job 1: Service
// [6:28 PM, 8/30/2021] Job 1: Sim Cange
// [6:28 PM, 8/30/2021] Job 1: Device with Fuel/Tempreture Sensor
  title="Add Job Card"
  addLat: any;
  btnText="Submit"
  addlng: any;
  AddMapObj: any;
  addressString: any;
  jobCardForm:FormGroup;
  installerSelect
  installerData
  installer
  installerObj: any;
  useridd: any;
  skip: number = 1;
  limit: number = 100;
  myInput: any;
  maindata;
  bsConfig: Partial<BsDatepickerConfig>;
  add:boolean=true
  number=[]
  constructor(private contactService:ContactService,private fb:FormBuilder,private reportService:ReportService,private router:Router) {
    this.bsConfig = Object.assign({ dateInputFormat: 'DD-MM-YYYY, h:mm:ss a' });
    reportService.JobCard.subscribe(data=>{
      console.log(data);
      this.maindata=data
      
    });
    for (let i = 1; i <= 100; i++) {
      this.number.push(i)
    }
   }

   patchValue(data){
    //  var main=JSON.parse(data)
    this.maindata=data
    if(data){
      console.log("IN",data);
      this.add=false
        this.title="Edit Job Card";
        this.btnText="Update"
        this.jobCardForm.patchValue({
JobType:data.JobType?data.JobType:'',
Description:data.Description?data.Description:'',
CustomerName:data.CustomerName?data.CustomerName:'',
Mobile:data.Mobile?data.Mobile:'',
Address:data.Address?data.Address:'',
Location:data.Location?data.Location:'',
NoOfInstallation:data.NoOfInstallation?data.NoOfInstallation:'',
Amount:data.Amount?data.Amount:'',
PaymentStatus:data.PaymentStatus?data.PaymentStatus:'',
Status:data.Status?data.Status:'',
Remarks:data.Remarks?data.Remarks:'',
Technician:data.Technician.first_name?data.Technician.first_name+' '+data.Technician.last_name:'',
JobDate:data.JobDate?data.JobDate:new Date()
        })

      }

      var temp  = data.Location.coordinates;
      var poiLat = temp[1];
      var poiLong = temp[0];
      var current_add = new google.maps.LatLng(poiLat, poiLong);
      var mapOptions = {
        zoom: 15,
        center: current_add
      };
  
      var map = new google.maps.Map(document.getElementById('poiAddMap'), 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(); 

   })
  }

  ngOnInit() {
    
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.getInstallerData() ;
    // this.patchValue()
    this.jobCardForm=this.fb.group({
      JobType:[''],
Description:[''],
CustomerName:[''],
Mobile:[''],
Address:[''],
Location:[''],
NoOfInstallation:[''],
Amount:[''],
PaymentStatus:[''],
Status:[''],
Remarks:[''],
Technician:[''],
JobDate:[new Date()]
    })
    if(localStorage.getItem('Carddata')){
      this.patchValue(JSON.parse(localStorage.getItem('Carddata')));
      localStorage.removeItem('Carddata')
    }
    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'));
      
    }
  

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

  save(){
    console.log(this.jobCardForm.value);
    if(!this.add){
       var data1={
  JobType:this.jobCardForm.value.JobType,
  Description:this.jobCardForm.value.Description,
  CustomerName:this.jobCardForm.value.CustomerName,
  Mobile:this.jobCardForm.value.Mobile,
  Address:this.jobCardForm.value.Address,
  Location:this.addLat?{ "coordinates": [this.addLat,this.addlng], type: "Point" }:this.maindata.Location,
  NoOfInstallation:this.jobCardForm.value.NoOfInstallation,
  Amount:this.jobCardForm.value.Amount,
  PaymentStatus:this.jobCardForm.value.PaymentStatus,
  Status:'complete',
  Remarks:this.jobCardForm.value.Remarks,
  Technician:this.installerSelect?this.installerSelect[0]?this.installerSelect[0]._id:undefined:undefined,
  SupAdmin:this.useridd,
  JobCompletedOn:new Date().toISOString()
  // JobDate:new Date(this.jobCardForm.value.JobDate).toISOString(),
  // CreatedDate:new Date().toISOString()
      }
      this.contactService.post('/JobCard/update?id='+this.maindata._id,data1).subscribe(res=>{
        console.log(res);
        this.router.navigate(['/JobCard'])
        
      })


    }else{
      var data={
  JobType:this.jobCardForm.value.JobType,
  Description:this.jobCardForm.value.Description,
  CustomerName:this.jobCardForm.value.CustomerName,
  Mobile:this.jobCardForm.value.Mobile,
  Address:this.jobCardForm.value.Address,
  Location:{ "coordinates": [this.addLat,this.addlng], type: "Point" },
  NoOfInstallation:this.jobCardForm.value.NoOfInstallation,
  Amount:this.jobCardForm.value.Amount,
  PaymentStatus:this.jobCardForm.value.PaymentStatus,
  Status:'pending',
  Remarks:this.jobCardForm.value.Remarks,
  Technician:this.installerSelect?this.installerSelect[0]?this.installerSelect[0]._id:undefined:undefined,
  SupAdmin:this.useridd,
  JobDate:new Date(this.jobCardForm.value.JobDate).toISOString(),
  CreatedDate:new Date().toISOString()
      }
      this.contactService.post('/JobCard/add',data).subscribe(res=>{
        console.log(res);
        this.router.navigate(['/JobCard'])
        
      })

    }
    
  }

 getInstallerData(){
  this.contactService.getTechnician(this.useridd, this.skip, this.limit,this.myInput,false).subscribe(
    (res:any)=>{
      this.installerData=res;
       for(let i=0;i<this.installerData.length;i++){
          this.installerData[i].fullName=this.installerData[i].first_name+' '+this.installerData[i].last_name;
        }
    })
}
 

    filtergrpStatess12(val) {
  console.log(val)
  if (val) {

    const filtergrpValue:any = val;
    this.installerSelect=[];
     this.installerSelect = this.installerData.filter(function(g){
      var c = (g.first_name).toLocaleLowerCase().indexOf(filtergrpValue.toLocaleLowerCase());
    //  this.option = this.options[i];
    console.log("TESTINg",c)
      return c > -1;    
    });
    if(this.jobCardForm.value.Technician){
      for(let i=0;i<this.installerData.length;i++){
        if(this.installerData[i].fullName==this.installer){
          this.installerObj=this.installerData[i]._id
          console.log(this.installerData[i]);
          
          // this.getUser(this.installerData[i]._id)
        }
      }
    }
      console.log(this.installerSelect,this.installer, this.installerObj);
      return this.installerSelect;
  }

}

}
