import { Title } from '@angular/platform-browser';
import { tap, take, map, catchError, switchMap, shareReplay, retry } from 'rxjs/operators';
import { of, BehaviorSubject, Subject, combineLatest } from 'rxjs';
import { State } from '@progress/kendo-data-query';
import { MessageService } from '../_shared/services/message.service';
import { Validators } from '@angular/forms';
import { DialogService, DialogSettings } from '@progress/kendo-angular-dialog';
import { NotifyService } from '../_shared/services/notify.service';
import { saveAs } from '@progress/kendo-file-saver';
import * as util from '../_shared/utils/util';
import { LocationService, RequiredData, SaveType, Item, Detail } from './location.service.service';
import { CustomFormBuilder } from '../_shared/services/custom-form-builder.service';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostListener, inject, ViewChild, ViewEncapsulation } from '@angular/core';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../app.config';

@Component({
  selector: 'app-location',
  templateUrl: './location.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FAST_PAGE_COMMON, FAST_KENDO_COMMON]
})
export class LocationComponent {
  @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
  };

  private service = inject(LocationService);
  private messageService = inject(MessageService);
  private titleService = inject(Title);
  private fb = inject(CustomFormBuilder);
  private ref = inject(ChangeDetectorRef);
  private dialogService = inject(DialogService);
  private notify = inject(NotifyService);

  constructor() {
    this.LocationForm = this.getLocationForm()
    this.LocationInitialValues = this.LocationForm.getRawValue() as Detail;
  }

  util = util;

  isAddNew: boolean;
  LocationForm: util.FormModel<Detail>;
  gridScrollPosition: util.GridScrollPosition = { topPos: 0, leftPos: 0 };
  localRequiredData: RequiredData;
  hasModifyPermission = false;
  LocationInitialValues: Detail;
  mySelection: number[] = [];

  gridLoading$ = new BehaviorSubject<boolean>(true)
  refreshLocation$ = new BehaviorSubject<string>(null)
  exporting$ = new BehaviorSubject<boolean>(false)
  detailOpened$ = new BehaviorSubject<boolean>(false)
  refreshRequiredData$ = new BehaviorSubject(null)
  detailLoading$ = new BehaviorSubject<boolean>(true)
  refreshDetail$ = new BehaviorSubject<string>(null)
  save$ = new Subject<SaveType>()
  delete$ = new Subject()
  exportClicked$ = new Subject()

  state: State = {
    filter: null,
    group: null,
    skip: 0,
    sort: [{ field: 'LocationName', dir: 'asc' }],
    take: 50
  };

  getLocationForm() {
    const fb = this.fb;
    const fg: util.FormModel<Detail> = fb.group({
      locationName: fb.ctr(null, Validators.required),
      locationId: fb.ctr(0),
    });

    return fg;
  }

  requiredData$ = this.refreshRequiredData$.pipe(
    tap(() => this.detailLoading$.next(true)),
    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)
  )

  location$ = this.refreshLocation$.pipe(
    tap(() => {
      this.gridLoading$.next(true);
    }),
    switchMap(() => {
      return this.service.getLocation(this.state);
    }),
    tap(() => {
      this.gridLoading$.next(false);
      util.goToSavedGridScrollPos(this.kendoGridEl, this.gridScrollPosition);
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService);
    }), retry(10)
  )

  exportAction$ = this.exportClicked$.pipe(
    tap(() => {
      this.exporting$.next(true);
    }),
    switchMap(() => {
      return this.service.exportLocation(this.state, 'Locations.xlsx');
    }),
    tap(res => {
      saveAs(res.fileBlob, res.fileName);
      this.exporting$.next(false);
    }),
    shareReplay(1),
    catchError(err => {
      this.exporting$.next(false);
      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(LocationName => {
      this.detailLoading$.next(true);
      this.LocationForm.disable();
      this.LocationForm.reset();
      if (LocationName == null)
        return of(this.LocationInitialValues);
      else
        return this.service.getDetail(LocationName);
    }),
    map(result => {
      const detail: Detail = result;
      if (detail) {
        util.convertToDates(detail);
        this.LocationForm.setValue(detail);
      }
      return detail;
    }),
    tap(() => {
      this.locationFinishedLoading();
    }),
    shareReplay(1),
    catchError(err => {
      this.closeLocation(false);
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  saveResult$ = this.save$.pipe(
    switchMap(saveType => {
      this.detailLoading$.next(true);
      this.LocationForm.disable();
      const itemToSave = this.LocationForm.getRawValue() as Detail;
      return this.service.saveLocation(itemToSave, saveType);
    }),
    tap(saveResult => {
      this.notify.success('save successful');
      this.closeLocation(false);
      this.refreshLocation$.next(null);
      this.mySelection = [saveResult];
    }),
    shareReplay(1),
    catchError(err => {
      this.locationFinishedLoading();
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  deleteResult$ = this.delete$.pipe(
    switchMap(() => {
      this.detailLoading$.next(true);
      this.LocationForm.disable();
      const itemToDelete: Detail = this.LocationForm.getRawValue();
      return this.service.deleteLocation(itemToDelete.locationName);
    }),
    tap(() => {
      this.notify.success('delete successful');
      this.locationFinishedLoading();
      this.closeLocation(false);
      this.refreshLocation$.next(null);
    }),
    shareReplay(1),
    catchError(err => {
      return util.handleError(err, this.messageService)
    }), retry(10)
  )

  openLocation(Name: string): void {
    util.saveGridScrollPos(this.kendoGridEl, this.gridScrollPosition);
    this.refreshDetail$.next(Name);
    this.detailOpened$.next(true);
  }

  onDetailClosing() {
    util.onDetailChanging(this.LocationForm, this.dialogService, this.closeLocation, this.save);
  }

  closeLocation = (isFromInterface: boolean) => {
    this.detailOpened$.next(false);

    if (isFromInterface)
      util.goToSavedGridScrollPos(this.kendoGridEl, this.gridScrollPosition);
  }

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

  add(): void {
    this.isAddNew = true;
    this.openLocation(null);
  }

  edit(dataItem: Item): void {
    this.isAddNew = false;
    this.openLocation(dataItem.LocationName);
  }

  save = (saveType: util.SaveType) => {
    this.LocationForm.markAllAsTouched();
    if (this.LocationForm.valid)
      this.save$.next(saveType);
    else
      this.notify.error("validation failed");
  }

  delete(): void {
    const deleteConfirmSettings: DialogSettings = {
      title: "Please confirm",
      content: "Are you sure you want to delete this item?",
      actions: [{ text: 'No' }, { text: 'Yes', cssClass: 'k-primary' }],
      cssClass: 'utilPrompt'
    }

    this.dialogService.open(deleteConfirmSettings).result.pipe(take(1)).subscribe(result => {
      if (util.getDialogAction(result) === util.dialogAction.Yes)
        this.delete$.next(null);
    });
  }

  export(): void {
    this.exportClicked$.next(null);
  }

  dataStateChange(state: State): void {
    this.gridScrollPosition.topPos = 0;
    this.gridScrollPosition.leftPos = 0;
    util.fixKendoQueryFilter(state.filter);
    this.state = state;
    this.refreshLocation$.next(null);
  }

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