import { Component, OnInit } from '@angular/core';
import { MdDialog } from '@angular/material';
import { Router } from '@angular/router';
import { ContactService } from '../contact.service';
declare var moment,$:any;
declare var swal:any;

@Component({
  selector: 'app-address-update',
  templateUrl: './address-update.component.html',
  styleUrls: ['./address-update.component.scss']
})
export class AddressUpdateComponent implements OnInit {
  addressArr:any=[];
  tabelObj: any;
  useridd: any;
  identifier:any='addressComponent'
  constructor(public dialog: MdDialog, private router: Router, private contactService: ContactService) { }

  ngOnInit() {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    var td= this.todate.setHours(0,0,0,0);
    this.todate = new Date(td);
    this.testTable();

  }


  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function() {
       that.tabelObj = $('#deviceTable').DataTable({
            'serverSide': true,
            "processing": true,
            "searching": false,
            pagingType: 'full_numbers',
            pageLength: 25,
            "scrollY":'65vh',
            // "ordering": true,
            order: [[0, 'desc']],  
            "scrollCollapse": true,     
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            ajax: (dataTablesParameters,callback) => {
              // dataTablesParameters.op = {};
              // dataTablesParameters.select = [];
              // dataTablesParameters.find = {};
              // dataTablesParameters.columns = [
              //     { data: "_id","orderable": "true" },
              //     { data: "address" },
              //     { data: "current_address" },
              //     { data: "createdBy.first_name" },
              //     { data: "createdBy.last_name" },
              //     { data: "createdOn" },
              //     { data: "status" },
              //     { data: "location.coordinates" },
              //     { data: null, defaultContent: '' }
              // ]

              // if (that.Fromdate) {
              //     var fdate = new Date(that.Fromdate).toISOString()
              //     dataTablesParameters.find['createdOn'] = dataTablesParameters.find['createdOn'] ? dataTablesParameters.find['createdOn'] : {};
              //     dataTablesParameters.find['createdOn']['$gte'] = fdate
              // };
            
              // if (that.todate) {
              //     var tdate = new Date(that.todate).toISOString()
              //     dataTablesParameters.find['createdOn'] = dataTablesParameters.find['createdOn'] ? dataTablesParameters.find['createdOn'] : {};
              //     dataTablesParameters.find['createdOn']['$lte'] = tdate;
              // }
              // dataTablesParameters.find['user'] = that.useridd;
              var suburl = "";
              suburl += "/googleAddress/test1";
              that.contactService.getApprovalAddressList(that.useridd).subscribe(resp => {
                  console.log("Response from datatable=>", resp); 
            
                  callback(resp);
              }, err => {
              
              });
            
          },  
          "rowCallback": function(row: Node, data: any | Object, index: number){
            $('#updateAddress',row).bind('click',()=>{
            

             
              // var warningMsg = "Are you sure that you want to permanently delete the selected device ?" ;
              swal({
                  // title: 'Are you sure?',
                  text: "Do you want to approve this address ?",
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Yes, approve'
                }).then((result: { value: boolean; }) =>{                      
                  if(result){
                    var payLoad={
                          lat : data.location.coordinates[1],
                          long: data.location.coordinates[0],
                          address : data.address,
                          mid: data._id
                    }
                      that.contactService.changeAddress(payLoad).subscribe(res=>{
                     
                          swal(
                              'Updated',
                              'Address Updated',
                              'success'
                            )

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

            },
        
            "columns": [
              {
                "data": "_id",
                "visible":false,
                "defaultContent": "",
                "render": function(data, type, row) {  
                  return data?data : '';                  
                }
            },
          
              {
                "data": "current_address",
                "defaultContent": "",
                "render": function(data, type, row) {  
                  return data?data : '';                  
                }
            },
                {
                    "data": "address",
                    "defaultContent": "",
                    "render": function(data, type, row) {  
                      return data?data : '';                  
                    }
                },
                {
                    "data": "createdOn",
                    "defaultContent": "",
                    render: function(data, type, row) {
                      var expDate = new Date(data);
                      return data ? (moment(expDate).format('llll')) : "";  
                    }
                }, 
                {
                  "data": "status",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    return data?data:'';        
                  }
              }, 
                {
                  "data": "createdBy",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    console.log(row);
                    var firstName=data.first_name?data.first_name:'';
                    var lastName=data.last_name?data.last_name:''
                    // var isUserename = row.user;
                    // if(isUserename != undefined){
                      // name = data.first_name?data.first_name:''
                      // :''+ ' '+ data.last_name?data.last_name:'';
                    // }
                    return firstName+' '+lastName; 
                  }
              }, 
              
              {
                "data": "location",
                "defaultContent": "",
                render: function(data, type, row) { 
                      return data?(data.coordinates[1] + ',' + data.coordinates[0]):'';
                }
            }  ,
            {                
              "data":null,
            
              "render":function(data,type,row){
                if(row.status == 'Pending'){
                  return '<i id="updateAddress" style="cursor:pointer;color:red" class="fas fa-exclamation-triangle" title="Approve address"></i>'
                }else{
                  return '<i class="far fa-check-circle" style="cursor:pointer;color:green" title="Approved"></i>'
                }
            
                     
              }
          }                      
            ],  

        });
  
    });
  
  }

  Fromdate= new Date();
  todate = new Date();

  getReport(event){
  
    console.log("inside function");
    if(event == 'getExcel'){
      this.exportExcel();
    }else{
      var deviceId: any;
      var tpdata = event ; 
      var that = this;
      var fd = new Date(tpdata.fromDate);
      var td  = new Date(tpdata.toDate);
  
      this.Fromdate = fd;
      this.todate = td;
       this.tabelObj.ajax.reload();  
   
    }
   
  }

  tab:any;
exportExcel()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#deviceTable').clone();
    table[0].querySelector("thead").remove();
    table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];//document.getElementById('deviceTable'); // id of table

    for(j = 0 ; j < this.tab.rows.length ; j++) 
    {     
        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
      
    }

    tab_text=tab_text+"</table>";
   
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

  

}
