import { Component, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, ElementRef, ViewEncapsulation, HostListener, inject } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { tap, map, catchError, switchMap, filter, shareReplay, retry } from 'rxjs/operators';
import { of, BehaviorSubject, Subject, combineLatest, zip } from 'rxjs';
import { MessageService } from '../_shared/services/message.service';
import { Validators } from '@angular/forms';
import { CustomFormBuilder } from '../_shared/services/custom-form-builder.service';
import { DialogService } from '@progress/kendo-angular-dialog';
import { NotifyService } from '../_shared/services/notify.service';
import * as util from '../_shared/utils/util';
import { SystemPasswordsService, Detail, RequiredData } from './system-passwords.service';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../app.config';
import { KENDO_LABEL } from '@progress/kendo-angular-label';

@Component({
  selector: 'app-SystemPasswords',
  templateUrl: './system-passwords.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FAST_PAGE_COMMON, FAST_KENDO_COMMON, KENDO_LABEL]
})
export class SystemPasswordsComponent {
  private service = inject(SystemPasswordsService);
  private messageService = inject(MessageService);
  private titleService = inject(Title);
  private fb = inject(CustomFormBuilder);
  private ref = inject(ChangeDetectorRef);
  private dialogService = inject(DialogService);
  private notify = inject(NotifyService);

  @ViewChild("grid", { read: ElementRef }) kendoGridEl: ElementRef;
  @HostListener('window:resize') onResize() {
    //this function is empty but for some reason it helps the window to resize faster
  };

  constructor() {

  }

  util = util;

  detailForm = this.getDetailForm();
  detailLoading$ = new BehaviorSubject<boolean>(true)
  refreshRequiredData$ = new BehaviorSubject(null)
  hasModifyPermission = false;
  localRequiredData: RequiredData;
  save$ = new Subject()
  refreshDetail$ = new BehaviorSubject<number>(null)
  refreshItems$ = new BehaviorSubject<string>(null)
  mySelection: number[] = [];
  detailInitialValues: Detail = this.detailForm.value as Detail;
  arePasswordsShown: boolean = false;

  getDetailForm() {
    const fb = this.fb;
    const fg: util.FormModel<Detail> = fb.group({
      showPasswords: fb.ctr(false, Validators.required),
      dealAlter: fb.ctr(null, Validators.required),
      arapAlter: fb.ctr(null, Validators.required),
      overdueAlter: fb.ctr(null, Validators.required),
      pdfEdit: fb.ctr(null, Validators.required),
      accountingExport: fb.ctr(null, Validators.required)
    });

    return fg;
  }

  requiredData$ = this.refreshRequiredData$.pipe(
    switchMap(refreshType => {
      return combineLatest([this.service.requiredData$, of(refreshType)]);
    }),
    map(([requiredData, refreshType]) => {
      this.localRequiredData = requiredData;
      if (refreshType === util.RefreshType.SelfOnly)
        this.detailLoading$.next(false);
      return requiredData;
    }),
    tap((requiredData) => {
      this.hasModifyPermission = requiredData.hasModifyPermission;
      util.focusInputTarget()
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  localDetailLoading = true;
  detailLoadingWatcher$ = this.detailLoading$.pipe(
    tap(isLoading => {
      this.localDetailLoading = isLoading;
    }),
    shareReplay(1)
  )

  detail$ = this.refreshDetail$.pipe(
    switchMap(id => {
      this.detailLoading$.next(true);
      this.detailForm.disable();
      this.detailForm.reset();
      if (id === 0)
        return of(this.detailInitialValues);
      else
        return this.service.getDetail(id);
    }),
    map(result => {
      const detail: Detail = result;
      detail.showPasswords = false;
      if (detail) {
        util.convertToDates(detail);
        this.detailForm.setValue(detail);
      }
      return detail;
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  detailAndRequiredData$ = zip(this.detail$, this.requiredData$).pipe(
    tap(() => {
      this.detailFinishedLoading();
    })
  )

  saveResult$ = this.save$.pipe(
    switchMap(() => {
      this.detailLoading$.next(true);
      this.detailForm.disable();
      const itemToSave: Detail = this.detailForm.value as Detail;
      return this.service.saveDetail(itemToSave);
    }),
    tap(saveResult => {
      this.notify.success('save successful');
      this.mySelection = [saveResult];
      this.detailFinishedLoading();
    }),
    shareReplay(1),
    catchError(err => {
      this.detailFinishedLoading();
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  detailFinishedLoading(): void {
    this.detailForm.enable();
    this.detailLoading$.next(false);
    util.focusInputTarget();
  }

  save(instance: SystemPasswordsComponent): void {
    instance.detailForm.markAllAsTouched();
    if (instance.detailForm.valid)
      instance.save$.next(null);
    else
      instance.notify.error("validation failed");
  }

  title$ = of('System Passwords').pipe(
    tap((title) => util.trySetTitle(this.titleService, title))
  )

  showPasswordsChanged$ = this.detailForm.get('showPasswords').valueChanges.pipe(
    filter(() => {
      return !this.localDetailLoading;
    }),
    tap(() => {
      this.arePasswordsShown = this.detailForm.get('showPasswords').value;
    })
  )
}
