import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../contact.service';

@Component({
  selector: 'app-sho-route-plan',
  templateUrl: './sho-route-plan.component.html',
  styleUrls: ['./sho-route-plan.component.scss']
})
export class ShoRoutePlanComponent implements OnInit {
  routeForm:FormGroup;
  userId;
  location=[]
   data_descip: any;
  source: string;
  destination: string;
  constructor(private fb:FormBuilder,public dialogRef: MdDialogRef<ShoRoutePlanComponent>,@Inject(MD_DIALOG_DATA) public data: any,private contactService: ContactService) { 
    console.log(data);
    if(data.data.length>0){
      this.clocation_1(data.data[0].lat,data.data[0].lng,'source');
      this.clocation_1(data.data[data.data.length-1].lat,data.data[data.data.length-1].lng,'destination');
      data.data.forEach(element => {
        this.location.push([element.lng,element.lat])
      });
    }
  }

  ngOnInit() {
    this.userId = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.routeForm=this.fb.group({
      routeName:[''],
      source:[''],
      destination:['']
    })

    console.log(this.location,this.source,this.destination);
    
  }

  submit(){
    console.log(this.routeForm.value);

    let routeDetail={
      "src":this.routeForm.value.source,
      "dest":this.routeForm.value.destination,
      "name":this.routeForm.value.routeName,
      "user":this.userId,
      "path":this.location,
      "poi":[],
      "status":"Active",
      device:this.data.device.device_obj._id
    };

    console.log(routeDetail);
   
    console.log('this is final payload',routeDetail)
    this.contactService.saveRoute(routeDetail)
      .subscribe(res => {
        console.log(res);
        this.data_descip = "Route Path Saved Successfully";
      launch_toast();
      this.dialogRef.close();
        // this.router.navigateByUrl("vehicleRoute");
      })

      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", ""); }, 1500);
    }
  }
    
  clocation_1(lat,long,type) {
     console.log("IN");
     
    var outerThis = this;
    var la = '';

    let latLng = {
      lat: "0",
      long: "0"
    };
  
      latLng = {
        lat:lat ?lat : 0,
        long: long ? long : 0
      }
    
    outerThis.contactService.getAddressByApi(latLng).subscribe(res => {
      console.log("IN",res);
      if (res.message == "Address not found in databse") {
       if(type=="source"){
         this.routeForm.patchValue({
           source:""
         })
         this.source=""
       }else{
         this.routeForm.patchValue({
           destination:""
         })
         this.destination=""
       }
       
      } else {
         if(type=="source"){
           this.routeForm.patchValue({
           source:res.address
         })
         this.source=res.address
       }else{
           this.routeForm.patchValue({
           destination:res.address
         })
         this.destination=res.address
       }
        // latlngObj['address'] = res.address;

      }
       
    })

  }

}
