import { formatDate } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { tap, catchError, filter, map, switchMap } from 'rxjs/operators';
import { StudentPaymentService } from 'src/app/core/service/student-payment/student-payment.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
  selector: 'app-confirm',
  templateUrl: './confirm.container.html',
  styleUrls: ['./confirm.container.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConfirmContainer implements OnInit {
  confirmList$ = new Observable()
  constructor(
    private studentPaymentSV: StudentPaymentService,
    private swSV: SweetalertService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    this.getData()
  }

  getData(){
    return this.confirmList$ = this.studentPaymentSV.getAll().pipe(
      map((x:any) => x.filter(a => a.is_approve == null))
    )
  }

  confirm(data){
    if(data.length == 0){
      this.swSV.errText('กรุณาเลือกข้อมูล')
    } else {
      this.studentPaymentSV.confirmPayment(data).pipe(
        tap(x => this.swSV.saveSuccess()),
        tap(x => this.getData()),
        tap(x => this.cdr.detectChanges()),
        catchError(err => {
          this.swSV.err()
          return throwError(err)
        })
      ).subscribe()
    }
  }

  deletePayment(data){
    this.swSV.confirm().pipe(
      filter(x => x.isConfirmed),
      switchMap(x => {
        return this.studentPaymentSV.deletePayment(data).pipe(
          tap(x => this.swSV.removeSuccess()),
          tap(x => this.getData()),
          tap(x => this.cdr.detectChanges()),
          catchError(err => {
            this.swSV.errText(err.error)
            return throwError(err)
          })
        )
      })
    ).subscribe()
  }

  search(date){
    const newDate = formatDate(date, 'yyyy-MM-dd', 'en-US')
    if(date) return this.confirmList$ = this.studentPaymentSV.getByDate(newDate).pipe(
      map((x:any) => x.filter(a => a.is_approve == null))
    )
  }

}
