import { Component, OnInit } from '@angular/core';
import { LocalDataSource } from 'ng2-smart-table';
import { SmartTableData } from '../../@core/data/smart-table';
import { PageapiService } from '../pageapi.service';
import { NbToastrService, NbWindowControlButtonsConfig, NbWindowRef, NbWindowService } from '@nebular/theme';
import { UserFormComponent } from './user-form/user-form.component';


import {
  NbComponentStatus,
  NbGlobalLogicalPosition,
  NbGlobalPhysicalPosition,
  NbGlobalPosition,
 
  NbToastrConfig,
} from '@nebular/theme';

@Component({
  selector: 'ngx-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent  {
  settings = {
    actions: {
      
      position: 'right', // left|right
    },
    pager : {
      display : true,
      perPage:5
  },
    mode: 'external',
    add: {
      addButtonContent: '<i class="nb-plus" ></i>',
      createButtonContent: '<i class="nb-checkmark" ></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      index: {
        title: 'ID',
        type: 'number',
      },
      userName: {
        title: 'Name',
        type: 'string',
      },
      email: {
        title: 'E-mail',
        type: 'string',
      },
      mobileNo: {
        title: 'Mobile No',
        type: 'string',
      },
      role: {
        title: 'Role',
        type: 'string',
      }
     
    }
  };
  filteredItems: any[];
  searchTerm: string;
  public source: LocalDataSource = new LocalDataSource();
  minimize = false;
  maximize = false;
  fullScreen = true;
  close = true;
  formData:any=[]
  index = 1;
  destroyByClick = true;
  duration = 2000;
  hasIcon = true;
  logUser = JSON.parse(localStorage.getItem('email')).email;
  admin:any =[];
  position: NbGlobalPosition = NbGlobalPhysicalPosition.TOP_RIGHT;
  preventDuplicates = false;
  status: NbComponentStatus = 'primary';
 
  constructor(private toastrService: NbToastrService,private service: SmartTableData,public _api:PageapiService,private windowService: NbWindowService) {
    const data = this.service.getData();
  
    this.getuserlistApi()

   
    
  }

  onDeleteConfirm(event): void {
    console.log(event)
    let passData = event
   // if (window.confirm('Are you sure you want to delete?')) {
      //event.confirm.resolve();

   

      let deletedata  = {'isActive':event.isActive,'id':passData.id}
  
      this._api.addUserFormDetails (deletedata).subscribe(res => {
        if (res.status == 200) {
  console.log(res)
  this.getuserlistApi();
  if(event.isActive == 1){
    this.showToast('success', 'Active User Data Completed..!', '');
  }else{
    this.showToast('success', 'Inactive User Data Completed..!', '');
  }

        }else{
          this.showToast('warning', 'Somthing is Wrong...!', 'Edit User Data Failed..!');
        }
      })

   // } else {
   //   event.confirm.reject();
   // }
  }
  onCreateConfirm() {
    console.log("Create Event In Console")
    console.log();
    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    let config= {
      hasBackdrop: true,
      width: '500px',
      height: '300px',
    }
    const windowRef: NbWindowRef =  this.windowService.open(UserFormComponent, { title: `New User`, buttons: buttonsConfig , });
   


      // Subscribe to the afterClosed event
      windowRef.onClose.subscribe((data) => {
        // Handle the window closure
        console.log(data);
        if(data == 1){
          this.showToast('success', 'Data Saved Successfully', 'Add User Data Completed..!');
          this.getuserlistApi();
           console.log('Window closed 123');
        }else if(data == 0){
          this.showToast('warning', 'Somthing is Wrong...!', 'Add User Data Failed..!');
        }
      });
  }

  onSaveConfirm(event) {
    console.log("Edit Event In Console")
    console.log(event);

    const buttonsConfig: NbWindowControlButtonsConfig = {
      minimize: this.minimize,
      maximize: this.maximize,
      fullScreen: this.fullScreen,
      close: this.close,
    };
    const windowRef: NbWindowRef =  this.windowService.open(UserFormComponent, { title: `Edit User`, context: event
    , buttons: buttonsConfig  });
   


      // Subscribe to the afterClosed event
      windowRef.onClose.subscribe((data) => {
        // Handle the window closure
        console.log(data);
        if(data == 1){
          this.showToast('success', 'Data Changed Successfully', 'Edit User Data Completed..!');
          this.getuserlistApi();
           console.log('Window closed 123');
        }else if(data == 0){
          this.showToast('warning', 'Somthing is Wrong...!', 'Edit User Data Failed..!');
        }
       
      
      });
  }


  getuserlistApi(){
    let param ={}
    this._api.getusers(param).subscribe(async res => {
      console.log(res)
      if(res.status == 200){

       let passData =  res.data
       let admin = passData.filter(arr=>{return ( arr.role == 'ADMIN' || arr.role == 'FRONT-OFFICE' ) && arr.email != this.logUser }) 

       admin.forEach((element:any, index) => {
        element.index = index  +1       
        
      });
      //  console.log(data)

      this.admin = admin
    
       await this.source.load(admin);
       this.source.setPaging(1, 10, true);
   
      }
    })
  }


  private showToast(type: NbComponentStatus, title: string, body: string) {
    const config = {
      status: type,
      destroyByClick: this.destroyByClick,
      duration: this.duration,
      hasIcon: this.hasIcon,
      position: this.position,
      preventDuplicates: this.preventDuplicates,
    };
    const titleContent = title ? ` ${title}` : '';

    this.index += 1;
    this.toastrService.show(
      body,
      `${titleContent}`,
      config);
  }

  filterItems() {
    console.log(  this.searchTerm)
   
     if(  this.searchTerm !=''){
   
   
     this.filteredItems = this.admin.filter(item =>
       Object.values(item).some(value => {
         if (typeof value === 'string') {
           return value.toLowerCase().includes(this.searchTerm.toLowerCase());
         }
         return false;
       })
     );
     this.admin = this.filteredItems
   }else{
     console.log( 'fhjsgsajdhgasksjgfcckjsdfgckjsdhfk')  
   
     this.getuserlistApi()
   }
   
   
   
   console.log( this.filteredItems)
   }

   resetPassword(data){
    console.log(data)

    this.formData= new FormData();
    if(data.hasOwnProperty('id')){
      this.formData.append('id', data.id);
     
    }  
   
    this.formData.append('password', 'Test@123');
  

    this._api.addUserFormDetails (this.formData).subscribe(res => {
      if (res.status == 200) {
console.log(res)
this.showToast('success', 'Password Changed Successfully', '');
 
      }else{
        this.showToast('warning', 'Password Changed Failed', '');
      }
    })

   }
}
