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

@Component({
  selector: 'app-signature',
  templateUrl: './signature.container.html',
  styleUrls: ['./signature.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SignatureContainer implements OnInit {
  recipientSignature$ = new Observable()
  constructor(
    private dialog: MatDialog,
    private cdr: ChangeDetectorRef,
    private recipientSignatureSV: RecipientSignatureService,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    this.recipientSignature$ = this.recipientSignatureSV.getAll()
  }

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

  delete(uid){
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      concatMap(x => {
        return this.recipientSignatureSV.deleteData(uid).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => this.recipientSignature$ = this.recipientSignatureSV.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.recipientSignature$ = this.recipientSignatureSV.getAll()),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

  search(query){
    if(query) return this.recipientSignature$ = this.recipientSignatureSV.search(`?${query}`)
  }

}
