import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import {Observable} from 'rxjs';
import {Router} from '@angular/router';
import { UserCountersService } from 'src/app/core/service/permission/user-counters.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { concatMap, filter, tap } from 'rxjs/operators';

@Component({
  selector: 'app-user-couter',
  templateUrl: './user-couter.container.html',
  styleUrls: ['./user-couter.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserCouterContainer implements OnInit {
  userCounterList$ = new Observable();

  constructor(
    private router: Router,
    private userCounterSV: UserCountersService,
    public swSV: SweetalertService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    this.userCounterList$ = this.userCounterSV.getAll()
  }

  add(){
    this.router.navigate(['user-counter/add']);
  }

  edit(id){
    this.router.navigate(['user-counter/edit', id]);
  }

  delete(id){
    console.log(id);
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.userCounterSV.deleteData(id).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => this.userCounterList$ = this.userCounterSV.getAll()),
          tap(x => this.cdr.detectChanges())
        )
      })
    ).subscribe()
  }

  search(query){
    if(query) return this.userCounterList$ = this.userCounterSV.search(`?${query}`);
    if(!query) return this.userCounterList$ = this.userCounterSV.getAll();
  }

}
