import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable, throwError } from 'rxjs';
import { catchError, concatMap, filter, switchMap, tap } from 'rxjs/operators';
import { OnlineCountersService } from 'src/app/core/service/settings/online-counters.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { FormDialogComponent } from '../../presenter/dialog/form-dialog/form-dialog.component';

@Component({
  selector: 'app-online-counter',
  templateUrl: './online-counter.container.html',
  styleUrls: ['./online-counter.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnlineCounterContainer implements OnInit {
  onlineCounter$ = new Observable()
  constructor(
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private onlineCounterSV: OnlineCountersService,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    this.onlineCounter$ = this.onlineCounterSV.getAll()
  }

  add(){
    const dialogRef = this.dialog.open(FormDialogComponent, {
      width: '500px',
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.onlineCounter$ = this.onlineCounterSV.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

  delete(uid){
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.onlineCounterSV.deleteData(uid).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => this.onlineCounter$ = this.onlineCounterSV.getAll()),
          tap(x => this.cdr.detectChanges()),
          catchError(err => {
            this.swSV.errText(err.error.description)
            return throwError(err)
          })
        )
      })
    ).subscribe()
  }

  edit(uid){
    const dialogRef = this.dialog.open(FormDialogComponent, {
      width: '500px',
      data : uid
    });
    dialogRef.afterClosed().pipe(
      tap(x => this.onlineCounter$ = this.onlineCounterSV.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

  search(query){
    if(query) return this.onlineCounter$ = this.onlineCounterSV.search(`?${query}`)
  }

}
