import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/internal/operators/filter';
import { concatMap, tap } from 'rxjs/operators';
import { AppUserService } from 'src/app/core/service/security/app-user.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
  selector: 'app-set-user',
  templateUrl: './set-user.container.html',
  styleUrls: ['./set-user.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SetUserContainer implements OnInit {
  userList$ = new Observable()
  constructor(
    private appUserSV: AppUserService,
    private swSV: SweetalertService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    this.userList$ = this.appUserSV.getAll()
  }

  delete(id){
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.appUserSV.deleteData(id).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => this.userList$ = this.appUserSV.getAll()),
          tap(x => this.cdr.detectChanges())
        )
      })
    ).subscribe()
  }

  search(query){
    if(query) return this.userList$ = this.appUserSV.search(`?${query}`)
    if(!query) return this.userList$ = this.appUserSV.getAll()
  }

}
