import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Output, EventEmitter, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { tap, catchError, switchMap, shareReplay, retry } 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 { SosSaveService } from './sos-supply-reset.service';
import * as util from '../../_shared/utils/util';
import { Validators } from '@angular/forms';
import { SosItem, SosDateRangeOptions } from '../models';
import dayjs from 'dayjs';
import { FAST_PAGE_COMMON, FAST_KENDO_COMMON } from '../../app.config';

@Component({
  selector: 'app-sos-crude-supply-reset[nomDate][sosItem]',
  templateUrl: './sos-supply-reset.component.html',
  styleUrls: ['./sos-supply-reset.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  imports: [FAST_PAGE_COMMON, FAST_KENDO_COMMON]
})
export class SosSupplyResetComponent implements OnInit {
  @Input() nomDate: Date;
  @Input() sosItem: SosItem;
  @Output() closed = new EventEmitter<boolean>()

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

  loading$ = new BehaviorSubject<boolean>(false);
  checksCompleted$ = new BehaviorSubject<boolean>(false);
  resetSupply$ = new Subject();
  resetSupplyResult$: Observable<object>;

  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.resetForm = this.getResetForm();

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

    util.focusAndSelectInputTarget();
  }

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

    return fg;
  }

  resetSupply() {
    this.resetSupply$.next(null);
  }

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

  restOfMonth() {
    if (this.resetForm.valid) {
      const fromDate = this.resetForm.value.fromDate;
      const monthEnd: Date = dayjs(fromDate).endOf('month').toDate();
      this.resetForm.patchValue({ toDate: monthEnd });
    }
  }
}
