import {Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {TestingPeriodService} from '../../../../../../core/service/testing-information/testing-period.service';
import {catchError, tap} from 'rxjs/operators';
import {BaseForm} from '../../../../../../core/base/base-form';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {throwError} from 'rxjs';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';

@Component({
  selector: 'app-change-time-section',
  templateUrl: './change-time-section.component.html',
  styleUrls: ['./change-time-section.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChangeTimeSectionComponent extends BaseForm implements OnInit  {
  time = '6:00 am';
  form;
  OldSectionTime;
  constructor(
    public fb: FormBuilder,
    public activeRoute: ActivatedRoute,
    public location: Location,
    public router: Router,
    private swSV: SweetalertService,
    private testingPeriodSV: TestingPeriodService,
    private cdr: ChangeDetectorRef,
  ) {
    super(
      router,
      activeRoute,
      fb,
      location
    );
  }

  createForm(): FormGroup {
    return this.fb.group({
      testing_period_uid: null,
      testing_release_exam_dates: null,
      period_id: null,
      start_time: [null, Validators.required],
      print_start_time: null,
      print_end_time: null,
      testing_information_uid: null,
      status_id: null,
      created_by: null,
      updated_by: null,
      updated_datetime: null,
      deleted_by: null,
      deleted_datetime: null,
    });
  }

  ngOnInit(): void {
    this.testingPeriodSV.get(this.id).pipe(
      tap(x => this.OldSectionTime = x),
      tap(x => this.form.patchValue(x)),
      tap(x => this.cdr.detectChanges()),
    ).subscribe();
  }

  save(){
    const form = this.form;
    // this.dialogRef.close({ event: 'close', data: form });
    this.testingPeriodSV.update2(form.getRawValue()).pipe(
      tap(x => this.swSV.updateSuccess()),
      tap(x =>  this.location.back()),
      catchError(err => {
        this.swSV.err()
        return throwError(err)
      })
    ).subscribe();
  }

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

  onChangeHour(data){
    this.form.get('start_time').setValue(data)
  }

}
