import { ContactService } from './../contact.service';
import { Component, OnInit } from '@angular/core';
import { FlashMessagesService } from 'angular2-flash-messages';
declare var $: any, DataTable: any;
declare var swal :any;
import * as moment from 'moment';
import { GpsEditMasterComponent } from '../gps-master/gps-edit-master/gps-edit-master.component';
import { MdDialog } from '@angular/material';

@Component({
  selector: 'app-user-master',
  templateUrl: './user-master.component.html',
  styleUrls: ['./user-master.component.scss']
})
export class UserMasterComponent implements OnInit {
  // @ViewChild(DataTableDirective)
  // datatableElement: DataTableDirective;
  Fromdate=new Date();
  todate=new Date();
  errorDialog: boolean;
  errorMsg: any;
  dataSelect = [];
  aa = [];

  identifier:String='usersMaster';
  userName:any;
  userName1:any;
  deleteduser :boolean = false;
  dtOptions: {

    pagingType: string; pageLength: number; serverSide: boolean; lengthMenu: (string | number)[][];
    processing: boolean; responsive: boolean; ajax: (dataTablesParameters: any, callback: any) => void; rowCallback: (row: Node, data: any, index: number) => Node; columns: ({
      title: string; data: string; "visible": boolean;
      "render": (data: any, type: any, row: any) => any;
    } | { title: string; data: string; "render": (data: any, type: any, row: any) => any; "visible"?: undefined; })[];
  };
  emailid: any;
  useridd: any;
  data1: any;
  costumers: any;
  dummyuserData: any = [];
  dummyuserData1: any = [];
  tabelObj: any;
  supadm: any;
  Load: boolean;
  userSelect1: any;


  constructor(public contactService: ContactService,public dialog: MdDialog,private _flashMessagesService: FlashMessagesService) {
    this.Fromdate.setHours(0, 0, 0);
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.supadm = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
  }

  ngOnInit() {
    // this.getUser();
    this.testTable();
    //  this.callfunction();
  }


  option: any;
  filterStates(option) {
  
    // console.log(option);

  }

  showDeleted : boolean = false ;
  delFlag : boolean = false;
  onChange(ev){
    
    this.showDeleted = ev.checked;

}


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


  testTable() {
    const that = this;

    $(document).ready(function () {
      that.tabelObj = $('#userTable').DataTable({
        'serverSide': true,
        "processing": true,
        "searching": false,
        "order": [[ 0, "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 : '_id',  "orderable": "true" },    
            { data: "first_name" },
            { data: "email" },
            { data: "phone" },
            { data: "isDealer" },
            { data: "pushNotification" },
            { data: "created_on" },
                 {data : "std_code"},

            { data: "Dealer.first_name" },
            { data: "Dealer.last_name" },
            { data: "last_name" },
            { data: "isSuperAdmin"}
              ]
              // this.userSelect._id
              dataTablesParameters.find.supAdmin = that.useridd;
                
          // if ((that.userSelect)&&(that.userSelect.length!=0)&&(that.userSelect[0].user_type!="All")) {
          //   dataTablesParameters.find._id = that.userSelect[0]._id;
          // }

          if (that.userSelect1 != undefined) {
            dataTablesParameters.find._id = that.userSelect1;
          }


          if (that.Fromdate) {
            dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
            dataTablesParameters.find['created_on']['$gte'] = {
              _eval: 'date',
              value: new Date(that.Fromdate).toISOString()
            }
          };
          // }
          if (that.todate) {
            dataTablesParameters.find['created_on'] = dataTablesParameters.find['created_on'] ? dataTablesParameters.find['created_on'] : {};
            dataTablesParameters.find['created_on']['$lte'] = {
              _eval: 'date',
              value: new Date(that.todate).toISOString()
            };
          }


          if(that.showDeleted === true){  
            dataTablesParameters.find.DeletedUser = {$exists : true};
            that.delFlag = true;
            console.log("called");

        
        }else{
            dataTablesParameters.find.DeletedUser = {$exists : false};
            that.delFlag = false;
            console.log("called");
        }

          // if(this.supadm){
          //   dataTablesParameters.find.supAdmin = that.useridd;
          // }
          
          var suburl = "";
          suburl += "/users/datatable";
          // console.log(suburl);
          // console.log(dataTablesParameters);
          // console.log(suburl)
          that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
            that.colSwitch()
            callback(resp);

          }, err => {
            // console.log(err);
            // console.log(err.status);
          });
        },
        "rowCallback": function(row: Node, data: any | Object, index: number){  
                  
          $('#edit', row).bind('click', () => {    
          // console.log("Edit Method",data);
          let dialogRef = that.dialog.open(GpsEditMasterComponent, {
            width: '650px',
            height: '700px',   
            data: {"userInfo":data}                      
          });

          dialogRef.afterClosed().subscribe(result => {   
            // console.log(result);
            if(result=="success"){
               that.callfunction();      
            }
          })  

          });
          
          $('#delete', row).bind('click', () => {
           
            var uid = data._id;
         
            that.contactService.deluser(uid)
                .subscribe(res => {
                   
                    that._flashMessagesService.show("User Deleted", { cssClass: 'alert-warning', timeout: 2000 });
                    that.Fromdate =new Date(); 
                    that.Fromdate.setHours(0, 0, 0);
                    that.todate =new Date();
                    that.todate;   
                    that.callfunction();   
                }, err => {
                     if(err.status==401){
                    var msg=JSON.parse(err._body);
                     console.log(msg);
                    this._flashMessagesService.show(msg.message, { cssClass: 'alert-warning', timeout: 2000 });
                 }else{
                  that._flashMessagesService.show("Internal Server Error", { cssClass: 'alert-warning', timeout: 2000 }); 

                }
                  
                })
        });
        $('#restoreDevice',row).bind('click',()=>{
          console.log('deviceRestore',data);
          that.contactService.restoreUser(data._id).subscribe(res=>{
              that._flashMessagesService.show("User Restored", { cssClass: 'alert-success', timeout: 2000 });
              that.callfunction()
          },err=>{
              that._flashMessagesService.show("Error while restoring User", { cssClass: 'alert-warning', timeout: 2000 });
          })
      });
      $('#pdelete',row).bind('click',()=>{
          console.log('permanent delete clicked=>',data);
         
          // var warningMsg = "Are you sure that you want to permanently delete the selected device ?" ;
          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){
                  that.contactService.permanentDeluser(data._id).subscribe(res=>{
                    that.callfunction();
                      swal(
                          'Deleted',
                          'Device Deleted',
                          'success'
                        )
                  })
              }                
            });
      })
          },
        "columns": [
          {
            "data": "first_name",
            "render": function (data, type, row) {
              return data ? (data + " " + row.last_name) : "";
            }
          },
          {
            "data": "Dealer",
            render: function (data, type, row) {
              return data ? (data.first_name + " " + data.last_name) : ""
            }
          },
          {
           "data": "isDealer",
            render: function (data, type, row) {
            return data?data:'false' ;
            }
          },
          {
            "data": "created_on",
            "render": function (data, type, row) {
              var created_time = new Date(data);

              return data ? (moment(created_time).format('llll')) : "";
            }
          },
          {
            "data": "email",
            render: function (data, type, row) {
              return data ? data : ""
            } 
          },
          {
            "data": "phone",
            "render": function (data, type, row) {
            //  console.log(row.std_code);
             var prefix:any;
             if(row.std_code){
             
               if(row.std_code.dialcode != undefined){
                  prefix = '+' + row.std_code.dialcode; 
               }else{
                   prefix  =  row.std_code ; 
               }

             }else{
           
               prefix = '';
             }
              return data ?(prefix + ' '+ data) : "";
            }
          },
          {
            "data": "pushNotification",
            "render": function (data, type, row) {
              var tokenCount = data ?  data.length :0;
              return tokenCount;
            }
          },
          {
            "data":null,"render":function(data,type,row){
            return '<button id="edit" type="button" class="btn btn-primary">Edit</button>'
          }
          },
          {                
            "data":null,
          
            "render":function(data,type,row){
                return '<button id="delete" type="button" class="btn btn-primary" style="background:red;border:0px;">Delete</button>'
                   
            }
        }, 
  
        {
            "data":null,
          
            "render":function(data,type,row){
                return '<button id="restoreDevice" type="button" class="btn btn-primary" style="background:#60ab1c;border:0px;">Restore</button>'                    
            }
    }         ,
    {                
        "data":null,
      
        "render":function(data,type,row){
            return '<button id="pdelete" type="button" class="btn btn-primary" style="background:red;border:0px;">Delete permanently</button>'
               
        }
    }     
        ],
        columnDefs: [
          {
            "searchable": true,
            "targets": [0,1,2,3],     
          },
        ]
      });
      that.colSwitch()
    });

  }

  // getUser() {
  //   this.Load = true;
  //   this.contactService.getContactsbyUser(this.useridd)
  //     .subscribe(res => {
  //       this.Load = false;
  //       // console.log("Alluserobject", res);
  //       this.costumers = res;
  //       console.log(this.costumers)
  //       this.dummyuserData = [];
  //       this.dummyuserData1 = [];
  //       var loadinguser = {
  //         user_type: "All",
  //         _id: "All User"
  //       }

  //       var loadinguser1 = {
  //         user_type: "All",
  //         _id: "All User"
  //       }
  //       this.dummyuserData.push(loadinguser);
  //       for (var i = 0; i < this.costumers.length; i++) {
  //          loadinguser = {
  //           user_type: this.costumers[i].first_name + " " + this.costumers[i].last_name,
  //           _id: this.costumers[i]._id
  //         }


  //         loadinguser1 = {
  //           user_type: this.costumers[i].phone,
  //           _id: this.costumers[i]._id
  //         }


  //         this.dummyuserData1.push(loadinguser1);
  //         this.dummyuserData.push(loadinguser);
  //       }
  //       console.log("phoneSearch Object = >",this.dummyuserData1);
  //     },err=>{
  //       this.Load = false;
  //     })
  // }

  // userSelect=[];
  // filterDealerStates(usr) {
  //   // console.log("userObj=>",usr);
  //   if(usr.length == 0){
  //     this.userSelect =[];
  //   }
  
  //   if (usr) {
      
  //     const filterdealerValue:any = usr;
  //     this.userSelect=[];
  //      this.userSelect = this.dummyuserData.filter(function(p){
  //       var t = p.user_type.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());
  //     //  this.option = this.options[i];
  //       return t > -1;    
  //     });
  //       // console.log("selectedUser=>",this.userSelect)
  //       return this.userSelect;
  //   }
  
  // }

  // userSelect1=[];
  // filterDealerStates1(usr1) {
  //   // console.log("userObj=>",usr);
  //   if(usr1.length == 0){
  //     this.userSelect1 =[];
  //   }
    
  //   if (usr1) {
  //     console.log("user=>",usr1);
  //     const filterdealerValue:any = usr1;
  //     this.userSelect1=[];
  //      this.userSelect1 = this.dummyuserData1.filter(function(ppp){
  //       var t = ppp.user_type.indexOf(filterdealerValue);
  //     //  this.option = this.options[i];
  //       return t > -1;    
  //     });
  //       // console.log("selectedUser=>",this.userSelect1)
  //       return this.userSelect1;
  //   }
  
  // }

  // userInformation() {
  
  //   this.testTable();
  // }

  colSwitch(){
   
if(this.supadm == true){
    // console.log("Inside function");
 
    for ( var k=0 ; k<11 ; k++ ) {
        if(this.delFlag == true){     
            // if(((k==15)||(k==16)||(k==17))){
            //     this.tabelObj.column( k ).visible( true );        
            // }
            // if(((k==13)||(k==14))){
            //     this.tabelObj.column( k ).visible( false );        
            // }

             this.tabelObj.column( 8 ).visible( false );          
            if((k== 9) || (k== 10)){
                this.tabelObj.column( k ).visible( true );
            }
        }else{
      
            this.tabelObj.column( 8 ).visible( true );          
            if((k== 9) || (k== 10)){
                this.tabelObj.column( k ).visible( false );
            }
        }
    }
}
}

tab:any;
exportExcel()
{

    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    var table = $('#userTable').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);
}

getReport(event){

  
  console.log("inside function",event);
  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);
  
    if(event.deletedUser === true){
      that.showDeleted = true;
    }

    if(event.userId != undefined){
      this.userSelect1 = event.userId[0];

    }
    this.Fromdate = fd;
    this.todate = td;
     this.tabelObj.ajax.reload();  
   
  }
 
}

}
