import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { CardPrintingTimeService } from 'src/app/core/service/card-print/card-printing-time.service';
import { BranchService } from 'src/app/core/service/settings/branch.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { TestingInformationService } from 'src/app/core/service/testing-information/testing-information.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SearchComponent implements OnInit {
  testingInfo;
  time;
  query = {
    testing_information_uid: null
  }
  constructor(
    private testingInfoSV: TestingInformationService,
    private cardSV: CardPrintingTimeService,
    private cdr: ChangeDetectorRef,
    private swSV: SweetalertService,
    private location: Location
  ) { }

  ngOnInit(): void {
    this.testingInfoSV.getAll().pipe(tap(x => this.testingInfo = x)).subscribe()
  }

  onSearch(){
    // console.log(this.query)
    this.cardSV.getTime(this.query.testing_information_uid).pipe(
      tap(x => this.time = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }

  displayBranch(item:string){
    if (item) return this.testingInfo.find(x => x.testing_information_uid == item)?.testing_information_name
  }

  save(){
    // console.log(this.time)
    this.cardSV.changeTime(this.time).pipe(
      tap(x => this.swSV.updateSuccess()),
      tap(x => this.location.back()),
      catchError(err => {
        this.swSV.err()
        return throwError(err)
      })
    ).subscribe()
  }

  cancel(){
    this.location.back()
  }

}
