import {Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {CheckAvailableSeatService} from '../../../../../../core/service/testing-register/check-available-seat.service';
import {catchError, tap} from 'rxjs/operators';
import {throwError} from 'rxjs';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {FormBuilder} from '@angular/forms';
import {UpdateTestingSeatService} from "../../../../../../core/service/testing-register/update-testing-seat.service";

@Component({
  selector: 'app-dialog-change-seat',
  templateUrl: './dialog-change-seat.component.html',
  styleUrls: ['./dialog-change-seat.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DialogChangeSeatComponent implements OnInit {
  seatData: any;
  form;
  constructor(
    private fb: FormBuilder,
    private dialogRef: MatDialogRef<DialogChangeSeatComponent>,
    private checkavailableseatSV: CheckAvailableSeatService,
    private updatetestingseatSV: UpdateTestingSeatService,
    private swSV: SweetalertService,
    private cdf: ChangeDetectorRef,
    @Inject(MAT_DIALOG_DATA) public data
  ) {
    this.form = this.fb.group({
      testing_subject_selected_uid: null,
      testing_seat: null
    });
  }

  ngOnInit(): void {
    console.log(this.data);
    this.checkseat(this.data);
  }

  checkseat(data){
    this.checkavailableseatSV.add(data).pipe(
      // tap(x => this.swSV.success('มีห้องว่าง')),
      // tap(x => console.log(x)),
      tap(x => {
        this.seatData = x;
        this.form.patchValue(this.data);
        this.cdf.detectChanges();
      }),
      catchError(err => {
        this.swSV.errText('ไม่มีห้องว่าง');
        this.dialogRef.close();
        return throwError(err);
      })
    ).subscribe();
  }

  save(){
    const form = this.form.getRawValue();
    console.log(this.form.getRawValue());
    this.updatetestingseatSV.updateSeat(form).pipe(
      tap(x => this.swSV.updateSuccess()),
      tap(x => this.dialogRef.close()),
      catchError(err => {
        this.swSV.err();
        this.dialogRef.close('err');
        return throwError(err);
      })
    ).subscribe();
  }

  cancel(){
    this.dialogRef.close();
  }

}
