import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import {ContactService} from '../contact.service';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { SelectUntrackVehiclesComponent } from './select-untrack-vehicles/select-untrack-vehicles.component';
declare var $: any;
declare var swal: any
import * as moment from 'moment';
@Component({
 selector: 'app-geofencing',
 templateUrl: './geofencing.component.html',
 styleUrls: ['./geofencing.component.scss'],
 providers: [ContactService]
})
export class GeofencingComponent implements OnInit {
 testCount=[1,2,3];
 circular_geofence =[];
fs :any;
Load: boolean;
tabelObj: any;
ls:any;
emailid:any;
or:any;
onn_time:any;
min:any;
corect_min:any;
hr:any;
before:any;
  tabelObj1: any;
  finalArr=[]
run(){

}
myaccount(){
 
 this.cond = false
 this.router.navigateByUrl("accountSettings");
 
 // let dialogRef = this.dialog.open(MyaccountComponent, {
 // width: '903px',
 // data: {}
 // });

 // dialogRef.afterClosed().subscribe(result => {

 // if(result == "succ"){
 // console.log("Updated")
 // }

 // });
}
openNav() {
 /* document.getElementById("myNav").style.width = "100%";
*/
 this.router.navigateByUrl("location");

}
 constructor(private router: Router,private contactService:ContactService,public dialog: MdDialog) {
 
 }
 myInput:any
 logout(){
 window.localStorage.clear();
 this.router.navigateByUrl("login");
 }
 devi(){
 this.router.navigateByUrl("dashboard");

 }
 soon(){
 this.router.navigateByUrl("const?_i="+window.localStorage.token);
 
 }

 
summaryReport(){

 this.cond = false
 this.router.navigateByUrl("device-report/summary-report");
}

group(){
 this.cond = false
 this.router.navigateByUrl("group_view");
}


 addgeo(){
 this.router.navigateByUrl("geofence-add");
 }
 geo(){
 this.router.navigateByUrl("geofencing");
 
 }

 geofancingReport(){
 this.cond = false
 this.router.navigateByUrl("device-report/geofancing");
 }


 overspeed(){
 this.cond = false
 this.router.navigateByUrl("device-report/overspeed");
 
 }
 
 
 stoppage_report(){
 this.cond = false
 this.router.navigateByUrl("device-report/stoppage_report");
 
 }
 

 vehicleRoute(){
 this.router.navigateByUrl("vehicleRoute");
 
 }
 
 dealerInfo(){
 this.cond = false
 this.router.navigateByUrl("dealerInfo");
 }
 
 ignition_report(){
 this.cond = false
 this.router.navigateByUrl("device-report/ignition_report");
 
 
 }
 route_map(){
 this.router.navigateByUrl("routeMapping");

 }
 routeViolation(){
 this.cond = false
 this.router.navigateByUrl("device-report/routeViolation");
 
 }
 alert_report(){
 this.cond = false
 this.router.navigateByUrl("device-report/alert_report");
 }

 notification(){
 this.cond = false
 this.router.navigateByUrl("notifications");
 }




 distance_report(){
 this.cond = false
 this.router.navigateByUrl("device-report/distance_report");
 }

 driverPerformance(){
 this.cond = false
 this.router.navigateByUrl("device-report/Driver-performance");
 }

 trip_report(){
 this.cond = false
 this.router.navigateByUrl("device-report/trip_report");
 
 }
 


 
 cond:Boolean = false;
 point : any = 0;
 a(){
//  console.log(this.point);
 if(this.point == 0){
 this.cond = true;
 this.point ++;
 }
 else if(this.point % 2 == 0){
 this.cond = true;
 this.point ++;
 }
 else{
 this.cond = false
 this.point ++;
 }
 
 
 }
 addcus(){
 this.router.navigateByUrl("add");
 }
 devicess:any;
 final:any;
 getdev(){
 let foods = []
 this.contactService.getDevice(this.emailid,this.useridd).subscribe(
 
 data => {
 this.devicess = data 
 
 let swap;
 for(let g = 0;g<this.devicess.devices.length-1;g++ ){
 for(let c = 0;c<this.devicess.devices.length-g-1;c++ ){
 if(this.devicess.devices[c].Device_Name>this.devicess.devices[c+1].Device_Name){
 swap = this.devicess.devices[c];
 this.devicess.devices[c] = this.devicess.devices[c+1];
 this.devicess.devices[c+1] = swap;
 }
 }
 }
 
 this.final = this.devicess.devices
 
 for(let i=0;i<this.devicess.devices.length;i++){
 
//  if(this.devicess.devices[i].type_of_device =="Tracker"){
 let a ={
 value : this.devicess.devices[i].Device_Name,
 viewValue:this.devicess.devices[i].Device_Name
 }
 foods.push(a);
//  console.log(a);
//  }
 
 }
 
 });
 }
 report(){
 this.cond = false
 this.router.navigateByUrl("device-report");
 
 }
 report_speed(){
//  console.log("report speed call")
 this.cond = false
 this.router.navigateByUrl("device-report/device-speed-report");
 }
 
de:any;
 delete(id){
var that=this
  swal({
                  // title: 'Are you sure?',
                  text: "Do you want to delete geofence?",
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Yes, delete'
                }).then((result: { value: boolean; }) =>{                      
                  if(result){
                    console.log(id);
                 
                   that.contactService.deleteGeoFence(id).subscribe(da => {
                      that.de = da
                      
                        swal(
                          'Deleted',
                          'Geofence deleted',
                          'success'
                        )

                        that.tabelObj.ajax.reload();
                  
                      });
              
                  }                
                });

 
//  console.log("delete called" +id)
//  this.contactService.deleteGeoFence(id).subscribe(
 
//  da => {
//  this.de = da
//   this.tabelObj.ajax.reload()
 
//  });
 
 
 }

 useridd:any;

 geostatus:any;
 foods = [];
 vewdev(a){
 this.router.navigateByUrl("geofencing-view?_i="+a);
 }

 vewdev_1(b){
     var drawCircle ={
         poiname  : b.poi.poiname,
         address : b.poi.address,
         latlong : b.poi.location.coordinates,
         radius : b.radius,
         identifier : 'circular'
     }
  
    this.router.navigateByUrl("geofencing-view?_i="+drawCircle);
 }
 googlemapview(){
 this.router.navigateByUrl("geofencing-view2");
 }
 mydealer(){
 window.localStorage['token'] = window.localStorage['Dealer_token'];
 localStorage.removeItem('devices');
 window.localStorage['DataUpdate'] = 'True';
 if(window.localStorage['DataLoaded'] = 'True'){
 window.localStorage['Custumer'] = 'OFF'
 this.router.navigateByUrl("add")
 // this.router.navigateByUrl("const?_status="+"OK");
 }
 }
 onChange(a,b,c,d){
 
 this.contactService.statusUpdateGeoFence(a,Boolean(b),Boolean(c),Boolean(d)).subscribe(
 
 geo => {
 this.geostatus = geo
 
 });
 /* console.log(a.checked);
 let status = a.checked;
 let g_id = b;
 this.contactService.statusUpdateGeoFence(status,g_id).subscribe(
 
 geo => {
 this.geostatus = geo
 
 }); */
 }
 geo_status:any;
 custtype:any;
 cust:boolean=false;
 devicesss:any;
 ideal(){
 this.router.navigateByUrl("device-report/ideal-report");
 }
 ign(){
 this.router.navigateByUrl("device-report/ign-report");
 
 }
 table1ch(){
 
 myFunction();
 function myFunction() {
 var input, filter, table, tr, td, i,td1;
 input = document.getElementById("myInput");
 
 filter = input.value.toUpperCase();
 table = document.getElementById("myTable");
 tr = table.getElementsByTagName("tr");
 for (i = 0; i < tr.length; i++) {
 td = tr[i].getElementsByTagName("td")[1];
 td1= tr[i].getElementsByTagName("td")[0]
 if (td) {
 if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
 tr[i].style.display = "";
 } 
 else if(td1.innerHTML.toUpperCase().indexOf(filter) > -1){
 tr[i].style.display = "";
 }
 else {
 tr[i].style.display = "none";
 }
 } 
 }
 }
 }
 mb:any;
 logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
superAdmin:Boolean = false;
 ngOnInit() {
 
 this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
 
 this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
 this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
 this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
 this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
 this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
 this.mb = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;

 this.custtype = JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
 //this.getdev();
 if(this.custtype == true){
 this.cust = true;
 }
 if(this.mb.charAt(0)=="n"){
 this.mb = ' '
 }
 if( window.localStorage['Custumer'] == 'ON'){
 this.logoutbut = false
 this.dealer = true
 }
 else{
 this.logoutbut = true
 }

 this.logo=window.localStorage['logo'];
 this.text=window.localStorage['text'];
 this.testTable();
 this.testTable1() ;
 var _thisDoc = this;
    $('#geofence').on('click', '.btn-circle', function(){
      _thisDoc.CO(this.id);
    });
//  this.getAllGeofences()
 
 
 }
CO(e) {
    console.log(e); //row.KC value
  } 
 getAllGeofences(){
this.contactService.getallgeofence(this.useridd).subscribe(
 data => {
 this.devicesss = data 
 this.geo_status = this.devicesss.status;

 });
 }

 total =0;
 t:any=0;
 public doughnutChartType:string = 'doughnut';
 statusArr = [0,0,0];
 statusList=['Loading','Unloading','Parking'];
 geofence_info=[];
 geofence=[];
 GeofenceGridData(){ 
 this.geofence=[];
//  console.log(this.useridd);
 this.contactService.getGeoFenceData(this.useridd)
 .subscribe(res=>{
//  console.log(res);
 this.geofence_info = res;
//  console.log(this.geofence_info.length);

 for(var i = 0;i<this.geofence_info.length;i++) {
 let group_logs = this.geofence_info[i];
//  console.log(group_logs);
 let _id = group_logs._id.vehicleGroupName;
 let group_name = group_logs._id.vehicleGroupName.toUpperCase();
 let statusListArr = group_logs.geoType;
 this.total = 0;
 this.t=0;
 this.statusArr = [0,0,0];
 if(statusListArr){
 for(var j=0;j<statusListArr.length;j++){
 var index = this.statusList.indexOf(statusListArr[j].type);
 if(index>-1){
 this.statusArr[index] = (statusListArr[j].count);
 }
 this.total += statusListArr[j].count;
 this.t += statusListArr[j].count;
 }
 }
 this.geofence.push({
 "_id":_id,
 "name":group_name,
 "statusCount" : this.statusArr,
 "totalCount" : this.total,
 "statusList" : this.statusList,
 "t":this.t 
 })
//  console.log(this.geofence);
 }
 },err=>{
//  console.log("error");
 })
 }

 Ddetail(){
 this.router.navigateByUrl("driverdetail");
 }
 DModel(){
 this.router.navigateByUrl("deviceModel");
 }
 VType(){
 this.router.navigateByUrl("VehicleType");
 }

 selectedIndex:number=0;
 showVehiclesByGroup(group,ev){

 this.contactService.getfilteredgeofance(group._id,this.useridd)
 .subscribe(res=>{
//  console.log(res);
 this.devicesss=res;
 this.geo_status = this.devicesss.status;
 this.selectedIndex=0;
 })
 
 }

 selectedIndexChange(val :number ){
 this.selectedIndex=val;
//  console.log(this.selectedIndex);
 }

 options = { 
 legend: {
 display: false
 },
 cutoutPercentage: 75
 };

 public doughnutChartColor: Array<any> = [
 {
 backgroundColor: ['lime','green','tomato']
 }
 ];

 getPOI(){

  this.tabelObj1.ajax.reload()

  //   var suburl = "";
  //   suburl += "/poi/poidatatable";

  //   var dataTablesParameters = {
  //       "draw": 1,
  //       "columns": [
  //         {
  //           "data": "user"
  //         },
  //         {
  //           "data": "radius"
  //         },
  //         {
  //           "data": "poi.location.coordinates"
  //         },
  //         {
  //           "data": "poi.poiname"
  //         },
  //         {
  //           "data": "createdOn"
  //         },
  //         {
  //           "data": "status"
  //         },
  //         {
  //           "data": "poi.address"
  //         },
  //         {
  //           "data": "untrackedDevice"
  //         }
  //       ],
  //       "order": [
  //         {
  //           "column": 3,
  //           "dir": "desc"
  //         }
  //       ],
  //       "start": 0,
  //       "length": 50,
  //       "search": {
  //         "value": "",
  //         "regex": false
  //       },
  //       "op": {},
  //       "select": [],
  //       "find": {
  //         "user": this.useridd
  //       }
  //     }
      
  // this.contactService.post(suburl, dataTablesParameters).subscribe(res=>{
  //     console.log('res=>',res['data']);
  //     this.circular_geofence = res['data'];
  //     return res['data']
  // },err=>{
  //     console.log(err);
  //     return []
  // })
 }

 updateGeofence(geoObj){
   console.log(geoObj);
   this.router.navigateByUrl("geofence-add?_i="+geoObj._id);
 }
 untrack(data){

  if(this.dialog.openDialogs && this.dialog.openDialogs.length > 0){
      return false;
    }
    let dialogRef = this.dialog.open(SelectUntrackVehiclesComponent, {
//  width: '503px',
//  height:'400px',
 data: data
 });
    dialogRef.afterClosed().subscribe((result) => {
      dialogRef = null;
      this.tabelObj.ajax.reload()
    if(result == "succ"){
      console.log("Updated")
    }
      //add code to perform any other actions on pop-up close.
    });

//     let dialogRef = this.dialog.open(SelectUntrackVehiclesComponent, {
// //  width: '503px',
// //  height:'400px',
//  data: data
//  });

//  dialogRef.afterClosed().subscribe(result => {
//    console.log(result);
   
//   this.tabelObj.ajax.reload()
//  if(result == "succ"){
//  console.log("Updated")
//  }

//  });
 }



testTable1() {
    const that = this;
    console.log("inside TABLE 1");
    $(document).ready(function () {
      that.tabelObj1 = $('#geofence1').DataTable({
        // dom: 'Bfrtip',
        // buttons: [ 'copy', 'csv', 'ex  cel', 'pdf', 'print' ],
        "autoWidth": true,
        'deferRender':true,
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
         "rowCallback": function(row: Node, data: any | Object, index: number){
          
         },
        ajax: (dataTablesParameters, callback) => {
           that.Load = true;
          var suburl = "";
    suburl += "/poi/poidatatable";

    var dataTablesParameters1 = {
        "draw": 1,
        "columns": [
          {
            "data": "user"
          },
          {
            "data": "radius"
          },
          {
            "data": "poi.location.coordinates"
          },
          {
            "data": "poi.poiname"
          },
          {
            "data": "createdOn"
          },
          {
            "data": "status"
          },
          {
            "data": "poi.address"
          },
          {
            "data": "untrackedDevice"
          }
        ],
        "order": [
          {
            "column": 3,
            "dir": "desc"
          }
        ],
        "start": 0,
        "length": 50,
        "search": {
          "value": "",
          "regex": false
        },
        "op": {},
        "select": [],
        "find": {
          "user": that.useridd
        }
      }
      
  that.contactService.post(suburl, dataTablesParameters1).subscribe(res=>{
      console.log('res=>',res['data']);
      for(var i=0;i<res['data'].length;i++){
        res['data'][i].radius=res['data'][i].radius?res['data'][i].radius:'N/A'
      }
       that.Load = false
        callback({ data: res['data'] });
  },err=>{
        that.Load = false
        callback({ data: [] });
  })
    
        },

        "columns": [
           {
            "data": "poi",
           
            "render": function (data, row) {  
              // console.log(row);
                         
              return data?data.poiname:'N/A';   
            }
          },
          {
            "data": "poi",
           
            "render": function (data, row) {             
              return data.address?data.address:'N/A';   
            }
          },
           {
            "data": "radius",
           "render": function (data, row) {             
              return data?data:'N/A';   
            }
          },

          {
            "data": "poi",
           "render": function (data, row) {             
              return data?data.location?data.location.coordinates?data.location.coordinates[1]:'N/A':'N/A':'N/A';   
            }
          },
          {
            "data": "poi",
           "render": function (data, row) {             
              return data?data.location?data.location.coordinates?data.location.coordinates[0]:'N/A':'N/A':'N/A';   
            }
          },
           {
            "data": "poi",
           "render": function (data, row) {             
              return row.status?row.status:'N/A';   
            }
          },
         
        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0,1,2,3,4,5] },
          {
            "targets": '_all',
            "createdCell": function (td, cellData, rowData, row, col) {
              $(td).css('padding', '18px')
            }
          },
          { "width": "10px", "targets": 0 },
          { "width": "40px", "targets": 1 },
          { "width": "100px", "targets": 2 },
          { "width": "70px", "targets": 3 },
          { "width": "70px", "targets": 4 },
           { "width": "70px", "targets": 5 },
          //  { "width": "70px", "targets": 6 },
          //  { "width": "70px", "targets": 7 },
          //  { "width": "70px", "targets": 8 },
          //  { "width": "70px", "targets": 9 },
          //  { "width": "70px", "targets": 10 },

        ], order: [[ 4, 'desc' ], [ 0, 'asc' ]]
      });

    });

  }

 testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#geofence').DataTable({
        // dom: 'Bfrtip',
        // buttons: [ 'copy', 'csv', 'ex  cel', 'pdf', 'print' ],
        "autoWidth": true,
        'deferRender':true,
        "processing": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
         "rowCallback": function(row: Node, data: any | Object, index: number){
          $('#entering', row).bind('click', () => {  
              var id=data._id 
               var entering=!data.entering;
               var exiting=data.exiting;
               var status=data.status
            that.onChange(id,status,entering,exiting)
                     
            });

            $('#status', row).bind('click', () => {  
              var id=data._id 
               var entering=data.entering;
               var exiting=data.exiting;
               var status=!data.status
            that.onChange(id,status,entering,exiting)
                     
            });

             $('#exiting', row).bind('click', () => {  
              var id=data._id 
               var entering=data.entering;
               var exiting=!data.exiting;
               var status=data.status
            that.onChange(id,status,entering,exiting)
                     
            });
            $('#edit', row).bind('click', () => {  
              that.updateGeofence(data)
                     
            });
             $('#delete', row).bind('click', () => {  
              that.delete(data._id)
                     
            });
             $('#track', row).bind('click', () => {  
              that.untrack(data)
                     
            });

             $('#view', row).bind('click', () => {  
             that.vewdev(data._id)
                     
            });
         },

         
        ajax: (dataTablesParameters, callback) => {
          console.log('temptemptemptemptemp', dataTablesParameters);
           that.Load = true;
          var suburl = "";
        that.contactService.getallgeofence(that.useridd).subscribe((res:any)=>{
        console.log(res);
        var j = 0;
        that.finalArr=[]
        if(res.length>0){
          for(var i=0;i<res.length;i++){
            res.type=res.type?res.type:'N/A'
            that.clocation_1(res[i],function(err,succ){
               if (err) {
                          console.log(err);
                          j++;
                        }
                else {
                          that.finalArr.push(succ);
                          
                          j++;
                          if (j === res.length) {
                            // that.endAddress=succ.address
                            that.Load = false;
                            callback({ data:  that.finalArr });
                          //    that.finalArr.sort(function(a:any,b:any){
                          // // return new Date(a.date).valueOf() - new Date(b.date).valueOf();
                          // });
                        }
            }
            })
          }

        }else{
             that.Load = false
        callback({ data: [] });
        }
        //  that.Load = false
        // callback({ data: res });
         },err=>{
             that.Load = false
        callback({ data: [] });
         })

        },

        "columns": [
           {
            "data": "type",
           
            "render": function (data, row) {  
              // console.log(row);
                         
              return data?data:'N/A';   
            }
          },
          {
            "data": "geoname",
           
            "render": function (data, row) {             
              return data?data:'N/A';   
            }
          },
           {
            "data": "entering",
            "render": function (data, type, row) {    
              var button 
              if(row.entering) {
                 button= `<input id='entering' type='checkBox' checked>`;
              } else{
                button=`<input id='entering' type='checkBox'>`;
              }
              return button 
            }
          },
          {
            "data": "exiting",
            "render": function (data, type, row) {    
              var button 
              if(row.exiting) {
               button= `<input id='exiting' type='checkBox' checked>`;
              } else{
                button=`<input id='exiting' type='checkBox'>`;
              }
              return button 
            }
          },
            {
            "data": "status",
            "render": function (data, type, row) {    
              var button 
              if(row.status) {
                button= `<input id='status' type='checkBox' checked>`;
              } else{
                button=`<input id='status' type='checkBox'>`;
              }
              return button 
            }
          },
            {
            "data": "devicesWithin",
            "render": function (data, type, row) {       
              return data?data.length:'N/A';   
            }
          },
          {
            "data": "area",
            "render": function (data, type, row) {       
              return data?((data/1000000)*247).toFixed(2):'N/A';   
            }
          },
           {
            "data": null,
            "render": function (data, type, row) {    
              
              return `<button class="btn btn=info btn-sm"><i id="edit"  style="font-size:20px;color: green" class="fas fa-edit"></i></button> `
            }
          },
           {
            "data": null,
            "render": function (data, type, row) {    
              
              return `<button class="btn btn=info btn-sm"><i id="delete" style="font-size:20px;color: red" class="fas fa-trash-alt"></i></button> `
            }
          },

           {
            "data": null,
            "render": function (data, type, row) {    
              
              return `<button class="btn btn=info btn-sm"><i id="track" style="font-size:20px;color: blue" class="fa fa-car"></i></button> `
            }
          },
             {
            "data": null,
            "render": function (data, type, row) {    
              
              return `<button class="btn btn=info btn-sm"><i id="view" style="font-size:20px;color: blue" class="fa fa-eye"></i></button> `
            }
          },
         
        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0,1,2,3,4,5,6,7,8,9,10] },
          {
            "targets": '_all',
            "createdCell": function (td, cellData, rowData, row, col) {
              $(td).css('padding', '18px')
            }
          },
          { "width": "10px", "targets": 0 },
          { "width": "40px", "targets": 1 },
          { "width": "100px", "targets": 2 },
          { "width": "70px", "targets": 3 },
          { "width": "70px", "targets": 4 },
           { "width": "70px", "targets": 5 },
           { "width": "70px", "targets": 6 },
           { "width": "70px", "targets": 7 },
           { "width": "70px", "targets": 8 },
           { "width": "70px", "targets": 9 },
           { "width": "70px", "targets": 10 },

        ], order: [[ 4, 'desc' ], [ 0, 'asc' ]]
      });

    });

  }

   clocation_1(data,cb) {
     console.log("IN",data.geofence);
     var latlongArr=[];
     if(data.geofence.coordinates){
       if(data.geofence.coordinates[0].length>0){
         for(var i=0;i<data.geofence.coordinates[0].length;i++){
          latlongArr.push({"latitude": data.geofence.coordinates[0][i][1], "longitude": data.geofence.coordinates[0][i][0] })
          if(i==(data.geofence.coordinates[0].length-1)){
            this.contactService.post('/hulls/calculateArea',{points:latlongArr}).subscribe((res:any)=>{
              data.area=res.area;
             cb(null,data)
            },err=>{
              data.area=0;
             cb(null,data)
            })

          }
         }
       }
     }

  }

  

}