import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Output, EventEmitter, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { tap, catchError, switchMap, shareReplay, retry, map } from 'rxjs/operators';
import { BehaviorSubject, Subject, Observable } from 'rxjs';
import { MessageService } from '../../_shared/services/message.service';
import { CustomFormBuilder } from '../../_shared/services/custom-form-builder.service';
import { DialogService } from '@progress/kendo-angular-dialog';
import { NotifyService } from '../../_shared/services/notify.service';
import { RequiredData, SosSaveService } from './sos-transfer-change-dates.service';
import * as util from '../../_shared/utils/util';
import { Validators } from '@angular/forms';
import { SosItem, SosDateRangeOptions } from '../models';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../../app.config';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-sos-gas-transfer-change-dates[sosItem]',
  templateUrl: './sos-transfer-change-dates.component.html',
  styleUrls: ['./sos-transfer-change-dates.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  imports: [FAST_PAGE_COMMON, FAST_KENDO_COMMON, DatePipe]
})
export class SosTransferChangeDatesComponent implements OnInit {
  @Input() sosItem: SosItem;
  @Output() closed = new EventEmitter<boolean>()

  util = util;
  icons = util.icons;
  changeForm: util.FormModel<SosDateRangeOptions>;

  loading$ = new BehaviorSubject<boolean>(false);
  checksCompleted$ = new BehaviorSubject<boolean>(false);
  changeDates$ = new Subject<void>();
  changeDatesResult$: Observable<object>;
  requiredData$: Observable<RequiredData>;

  constructor(private messageService: MessageService, private titleService: Title, private service: SosSaveService, private fb: CustomFormBuilder, private ref: ChangeDetectorRef, private dialogService: DialogService, private notify: NotifyService) {

  }

  ngOnInit(): void {
    this.changeForm = this.getChangeForm();

    this.requiredData$ = this.service.getRequiredData(this.sosItem).pipe(
      map(result => {
        util.convertToDates(result);
        return result;
      }),
      tap(result => {
        this.changeForm.enable();
        this.changeForm.patchValue({ fromDate: result.sourceSupplyStartDate, toDate: result.sourceSupplyEndDate });
      }),
      shareReplay(1),
      catchError(err => {
        return util.handleError(err, this.messageService)
      }), retry(1)
    );

    this.changeDatesResult$ = this.changeDates$.pipe(
      switchMap(() => {
        this.loading$.next(true);
        this.changeForm.disable();
        const changeOps = this.changeForm.getRawValue() as SosDateRangeOptions;
        return this.service.changeDates(this.sosItem, changeOps.fromDate, changeOps.toDate);
      }),
      tap(() => {
        this.closed.emit(true);
        this.loading$.next(false);
      }),
      shareReplay(1),
      catchError(err => {
        this.loading$.next(false);
        this.changeForm.enable();
        return util.handleError(err, this.messageService);
      }), retry(10)
    );

    util.focusAndSelectInputTarget();
  }

  getChangeForm() {
    const fb = this.fb;
    const fg: util.FormModel<SosDateRangeOptions> = this.fb.group({
      fromDate: fb.ctr(null, Validators.required),
      toDate: fb.ctr(null, Validators.required),
      saveNotes: fb.ctr(null)
    });
    fg.disable();

    return fg;
  }

  changeDates() {
    this.changeForm.markAllAsTouched();
    if (this.changeForm.valid)
      this.changeDates$.next();
    else
      this.notify.error("validation failed");
  }

  close() {
    this.closed.emit(false);
  }
}
