import {Component, OnInit, ChangeDetectionStrategy, Output, EventEmitter, ChangeDetectorRef, Input} from '@angular/core';
import {createQueryStringFromObject} from '../../../../../shared/util/func';
import {formatDate} from '@angular/common';
import {map, tap} from 'rxjs/operators';
import {ActivatedRoute} from '@angular/router';
import {TestingControlsService} from '../../../../../core/service/testing-information/testing-controls.service';
import {MatDialog} from '@angular/material/dialog';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {TestingInformationService} from '../../../../../core/service/testing-information/testing-information.service';

@Component({
  selector: 'app-room-view-search',
  templateUrl: './room-view-search.component.html',
  styleUrls: ['./room-view-search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RoomViewSearchComponent implements OnInit {
  @Output() search = new EventEmitter();
  @Input() testingInfoData:any;
  query = {
    start_date: null,
    end_date: null,
    period_id: null,
    testing_information_uid: null,
    testing_room_name_th: null,
  };
  id;
  constructor(
    public activeRoute: ActivatedRoute,
    private testingControlSV: TestingControlsService,
    private cdr: ChangeDetectorRef,
    private dialog: MatDialog,
    private swSV: SweetalertService,
    private testingInfoSV: TestingInformationService
  ) { }

  ngOnInit(): void {
    this.activeRoute.params.pipe(
      tap(x => x.id ? this.id = x.id : this.id = null)
    ).subscribe();
    this.testingInfoSV.get(this.id).pipe(
      tap(x => this.testingInfoData = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe();
  }

  onSearch(){
    this.query.testing_information_uid = this.testingInfoData.testing_information_uid;
    if (this.query.start_date !== null && this.query.end_date !== null){
      if(this.query.start_date) this.query.start_date = formatDate(this.query.start_date, 'yyyy-MM-dd', 'en-US');
      if(this.query.end_date) this.query.end_date = formatDate(this.query.end_date, 'yyyy-MM-dd', 'en-US');
      let query = createQueryStringFromObject(this.query);
      this.search.emit(query);
    }else {
      this.swSV.errText('กรุณาใส่วันที่เริ่มต้นและสิ้นสุด')

    }

  }

  clear(){
    this.query = {
      start_date: null,
      end_date: null,
      period_id: null,
      testing_room_name_th: null,
      testing_information_uid: this.query.testing_information_uid
    };
  }

}
