import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
import { EditDeviceMasterComponent } from '../device/edit-device-master/edit-device-master.component';
import { MdDialog } from '@angular/material';
import { PoiMasterEditComponent } from '../poi-master-edit/poi-master-edit.component';
import { PoiMenuComponent } from '../poi-menu/poi-menu.component';
import { SelectUntrackVehiclesComponent } from '../geofencing/select-untrack-vehicles/select-untrack-vehicles.component';
import { TrackedUntrackedVehiclesComponent } from './tracked-untracked-vehicles/tracked-untracked-vehicles.component';
declare var $: any, DataTable: any;
declare var swal: any;

@Component({
  selector: 'app-poireport',
  templateUrl: './poireport.component.html',
  styleUrls: ['./poireport.component.scss']
})
export class POIreportComponent implements OnInit {
  tabelObj: any;
  useridd: any;

  constructor(public contactService: ContactService,public dialog: MdDialog) { }

  ngOnInit() {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.testTable() ;
  }

  callfunction(): void {
    this.tabelObj.draw();
    
}

testTable() {
    const that = this;

    $(document).ready(function() {
        that.tabelObj = $('#deviceTable').DataTable({
            serverSide: true,
            "processing": true,
            "searching": false,
            "order": [[ 3, "desc" ]],    
            ajax: (dataTablesParameters: any, callback) => {

                dataTablesParameters.op = {};
                dataTablesParameters.select = [];
                dataTablesParameters.find = {};


                // console.log(dataTablesParameters);
                // console.log("callback", callback);

                // dataTablesParameters.find = {
                //   _id: that.useridd         
                // };
                dataTablesParameters.columns = [
                    { data: "user" },             
                    { data: "radius" },                          
                    { data: "poi.location.coordinates" },
                    { data:"poi.poiname"},
                    { data : "createdOn"},
                    { data : "status"},
                    { data : "poi.address"},
                    {data : "poi.poi_type"},
                    { data : "untrackedDevice"}
                  ]
                  dataTablesParameters.find.user = that.useridd;
              
                var suburl = "";
                suburl += "/poi/poidatatable";
                // console.log(suburl);
                // console.log(dataTablesParameters);
                // console.log(suburl)
                that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
                    console.log("poiResp",resp);
                    callback(resp);
                }, err => {
                   
                    // console.log(err.status);
                });
            },
            "rowCallback": function(row: Node, data: any | Object, index: number){  
                $('#edit', row).bind('click', () => {    
                    // console.log("Edit Method",data);
                    data.actionId= "edit";
                    let dialogRef = that.dialog.open(PoiMasterEditComponent, {
                      data: {"poiData":data}                      
                    });
                  
                    dialogRef.afterClosed().subscribe(result => {                  
                        if(result=="success"){
                            swal(
                                'Updated',
                                'POI updated Successfully !',
                                'success'
                              )
                              that.callfunction();
                        }
                      })  
                  });
                   $('#track', row).bind('click', () => {  
                 that.untrack(data)
                     
                });
                  $('#delete', row).bind('click', () => {
                      console.log(data);
                    swal({
                        title: 'Are you sure?',
                        text: "You won't be able to revert this!",
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Yes, delete it!'
                      }).then((result: { value: boolean; }) => {
                        if (result) {
                            console.log(data);
                            that.contactService.deletePOI(data._id)
                                .subscribe(response=>{
                                    that.callfunction();
                                    swal(
                                        'Deleted!',
                                        'POI deleted Successfully !',
                                        'success'
                                      )
                                },err=>{
                                    swal(
                                        'Server Error',
                                        'Error occured while deleting POI , Please try after sometime !!!',
                                        'error'
                                      )
                                })           
                        }
                      })
                   
                  });


              },
            "columns": [
                {
                    "data": "poi.poiname",
                    "render": function(data, type, row) {
                        return data ? data : "";
                    }
                },
                {
                    "data": "poi.address",
                    render: function(data, type, row) {
                        // console.log(data);
                        return data ? data : "";
                    }
                 },
                 {
                    "data": "radius",
                    render: function(data, type, row) {
                        // console.log(data);
                        return data ? data : "";
                    }
                 },
                 {
                    "data": "poi.poi_type",
                    render: function(data, type, row) {
                        // console.log(data);
                        return data ? data : "";
                    }
                 },
                {
                    "data": "poi.location.coordinates",
                    render: function(data, type, row) {
                       
                        return data?data[1]:"" ;
                    }
                },
                {
                    "data": "poi.location.coordinates",
                    render: function(data, type, row) {
                       
                        return data?data[0]:"" ;
                    }
                },
                {
                    "data": "status",
                    "render": function(data, type, row) {            
                        return data?data:"";
                    }
                },
                 {
                    "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": "untrackedDevice",
                //     "render": function(data, type, row) {  
                //         console.log(data);          
                //         return data?data:"";
                //     }
                // }, 
                {
                    "data":null,"render":function(data,type,row){
                    return '<button id="edit" type="button" class="btn btn-primary" md-raised-button style="background:#2d32a9;border:0px;">Edit</button>'
                }
            } ,
                {
                    "data":null,"render":function(data,type,row){
                    return '<button id="delete" type="button" class="btn btn-primary" md-raised-button style="background:red;border:0px;">Delete</button>'
                }
            }  
                            
            ],
        });

        that.tabelObj.columns().every( function () {
            var that = this;
     
            $( 'input', this.footer() ).on( 'keyup change', function () {
                if ( that.search() !== this.value ) {
                    that
                        .search( this.value )
                        .draw();
                }
            } );
        } );
       
    });

}
 untrack(data){

  if(this.dialog.openDialogs && this.dialog.openDialogs.length > 0){
      return false;
    }
    let dialogRef = this.dialog.open(TrackedUntrackedVehiclesComponent, {
//  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.
    });

 }
Addpoi(){
    var data = {
        "actionId" :  "add"
    }
    let dialogRef = this.dialog.open(PoiMasterEditComponent, {
      data: {"poiData":data} , 
      width: '800px',         
    });

    dialogRef.afterClosed().subscribe(result => {                  
        if(result=="success"){
            swal(
                'Updated',
                'POI added Successfully !',
                'success'
              )
             this.callfunction();
        }
      })  

}
AddMiultiple(){
 let dialogRef = this.dialog.open(PoiMenuComponent, {
      data: {"poiData":''} , 
      width: '800px',         
    });

    dialogRef.afterClosed().subscribe(result => {  
        console.log(result);
                        
        if(result=="success"){
            swal(
                'Uploaded',
                'POI added Successfully !',
                'success'
              )
             this.callfunction();
        }
      }) 


}



}
