import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute } from '@angular/router';
import { filter, map, switchMap, tap } from 'rxjs/operators';
import { BaseSubList } from 'src/app/core/base/base-sub-list';
import { TestingControlsService } from 'src/app/core/service/testing-information/testing-controls.service';
import { TestingInformationService } from 'src/app/core/service/testing-information/testing-information.service';
import { DialogComponent } from '../dialog/dialog.component';
import {SweetalertService} from '../../../../core/service/sweetalert/sweetalert';
import {formatDate} from '@angular/common';
import {createQueryStringFromObject} from '../../../../shared/util/func';
import {query} from '@angular/animations';
import {compareSegments} from '@angular/compiler-cli/src/ngtsc/sourcemaps/src/segment_marker';

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ViewComponent extends BaseSubList implements OnInit {
  testingControlList: any = [];
  query = {
    start_date: null,
    end_date: null,
    period_id: null,
    testing_room_name_th: null,
  };
  testingInfoData;
  constructor(
    public activeRoute: ActivatedRoute,
    private testingControlSV: TestingControlsService,
    private cdr: ChangeDetectorRef,
    private dialog: MatDialog,
    private swSV: SweetalertService,
    private testingInfoSV: TestingInformationService
  ) {
    super(activeRoute)
   }

  ngOnInit(): void {
    this.swSV.loadingStart()
    this.testingControlSV.getNoRoomStatus(`?testing_information_uid=${this.id}`).pipe(
      map((x:any) => x.filter(data => data.room_status != true)),
      tap(x => this.testingControlList = this.updateMatTable(x)),
      tap(x => this.swSV.close()),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
    this.testingInfoSV.get(this.id).pipe(
      tap(x => this.testingInfoData = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }

  changeRoom(x){
    const obj = {
      data : x,
      testing_information: this.testingInfoData
    }
    this.query.start_date = formatDate(this.query.start_date, 'yyyy-MM-dd', 'en-US');
    this.query.end_date = formatDate(this.query.end_date, 'yyyy-MM-dd', 'en-US');
    const dialogRef = this.dialog.open(DialogComponent, {
      width: '500px',
      data: obj
    });

    dialogRef.afterClosed().pipe(
      switchMap(x => {
        return this.testingControlSV.getNoRoomStatus(`?testing_information_uid=${this.id}&start_date=${this.query.start_date}&end_date=${this.query.end_date}`).pipe(
          map((x:any) => x.filter(data => data.room_status != true)),
          tap(x => this.testingControlList.data = x),
          tap(x => this.cdr.detectChanges()))
      })
    ).subscribe()
  }

  search(){
    if (this.query.start_date !== null && this.query.end_date !== null){
      this.swSV.loadingStart()
      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');
      console.log(this.createQueryStringFromObject(this.query))
      this.testingControlSV.getNoRoomStatus(`?${this.createQueryStringFromObject(this.query)}`).pipe(
        map((x:any) => x.filter(data => data.room_status != true)),
        tap(x => this.testingControlList = this.updateMatTable(x)),
        tap(x => this.swSV.close()),
        tap(x => this.cdr.detectChanges())
      ).subscribe()
    }else {
      this.swSV.errText('กรุณาใส่วันที่เริ่มต้นและสิ้นสุด')
    }
  }

  createQueryStringFromObject(query){
    let queryStr: string = ''

    for (const key in query) {
      console.log(query[key]);
      if (query[key] != null) {
        queryStr += `${key}=${query[key]}&`
      }
    }
    let lastIndex = queryStr.lastIndexOf('&')
    queryStr = queryStr.slice(0,lastIndex)
    return queryStr
  }

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

}
