import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, inject, ChangeDetectorRef} from '@angular/core';

import { StaffView ,StaffSearch } from '../models';

/* ngRx */
/*
import { Store, select } from '@ngrx/store';
import * as validationActions from './store/actions/validationpoint.action';
import * as validationSelector from './store/selectors/validationpoint.selector';
import { appValidationState } from './store/reducers';
*/
import { take } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { Router } from '@angular/router';
import { StaffService } from './staff.service';
import { AuthenticationService } from '../user-services';
import { TableModule } from 'primeng/table';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { ButtonModule } from 'primeng/button';
import { InputTextModule } from 'primeng/inputtext';

@Component({
  selector: 'staff-list',
  templateUrl: './staff.component.html',
  imports:[TableModule,FormsModule,CommonModule,ButtonModule,InputTextModule],
  styleUrls: ['./staff.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class StaffComponent implements OnInit, OnDestroy{

  private subscription:Subscription = new Subscription();
  firstname = '';
  email = '';
  lastname = '';
  loading = false;
  userList:StaffView[] = [];
  private cd = inject(ChangeDetectorRef);
  msg ="[Staff component]";
 
  /*
  private store: Store<appValidationState>
  */
  constructor(  
    private staffService: StaffService,
    private authenticationService: AuthenticationService,
    private router: Router    
     ) {}
     getSearchCiteria(): StaffSearch {
    let criteria:StaffSearch = {
      email: this.email,
      firstName: this.firstname,
      lastName: this.lastname,
    };

    return criteria;

  }
  canSearch():boolean {
    let result = false;
    result = this.email !== "";
    result = result || this.lastname !== "";
    result = result || this.firstname !== "";
    return result;
  }
  ngOnInit(): void
  { 
    this.authenticationService.isHome = false;
    this.authenticationService.isReport = false;
  const prev = this.staffService.searchCriteria;
    let goload = true;
    if (prev.lastName !== '')
    { 
      this.lastname = prev.lastName;
      goload = true;
    }
    if (prev.firstName !== '')
    {
      this.firstname = prev.firstName;
      goload = true;
    }
    if (prev.email !== '')
    {
      this.email = prev.email;
      goload = true;
    }
    if (goload)
    {
      this.search();
    }
  }  
  getActive(active:boolean):string {
    let result = 'false-icon pi-times-circle';
    if (active)
      result = 'true-icon pi-check-circle';
    return result;
  }
  search():void {
    const canSearch = true; // this.canSearch();
    if (canSearch)
    {
      this.loading = true;
      const criteria = this.getSearchCiteria();
       this.staffService.searchCriteria = criteria;
      this.subscription.add(
      this.staffService.searchStaffs(criteria).subscribe( {
        next: result => {
          this.loading = false;
      //  console.log(this.msg + "search load Data", result);      
        this.userList = result.data;
        this.cd.detectChanges();
      }, 
      error: e => {      
      const message = e || e.message;
     // this.toastr.error(message);
     this.loading = false;
      console.log("error ", e);
      }
      }) 
    );
   }
  }
  newUser():void {
  //console.log("add new employee");
    this.router.navigate( ['/staff/new'], { queryParams: {returnUrl:'/staff' } });
  }
  edit(id: number) : void {
    //console.log("edit staff", id);
 this.router.navigate( ['/staff/'+id], { queryParams: {returnUrl:'/staff' } });
  }
  
  deleteItem(id: number): void {
    this.staffService.deleteStaff(id)
      .pipe(take(1))
      .subscribe({ next: result => {
      console.log(this.msg + " deleteItem success", result);
      //let data = this.dataSource.data;
      //let index: number = data.findIndex(d => d.id === id);
    //  console.log(this.msg + "delete from datasource");
      //data.splice(index, 1)
      //this.dataSource.data = data;
      },
      error: e => console.error(e)
    });
    //console.log(this.msg + "click button to delete");
  }
  
  ngOnDestroy() {
		this.subscription.unsubscribe();
	}
}

