import { Component, NgZone, inject, OnInit } from '@angular/core';
import { ActivatedRoute, Data, ParamMap, Router, RouterModule } from '@angular/router';
import { combineLatest, filter, Observable, Subscription, tap, map } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { HttpResponse } from '@angular/common/http';

import SharedModule from 'app/shared/shared.module';
import { sortStateSignal, SortDirective, SortByDirective, type SortState, SortService } from 'app/shared/sort';
import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SORT, ITEM_DELETED_EVENT, DEFAULT_SORT_DATA } from 'app/config/navigation.constants';
import { IUnitConverter } from '../unit-converter.model';
import { EntityArrayResponseType, UnitConverterService } from '../service/unit-converter.service';
import { UnitConverterDeleteDialogComponent } from '../delete/unit-converter-delete-dialog.component';

import { UnitConverterSearchFormService, UnitConverterSearchFormGroup } from './unit-converter-search-form.service';
import { IUnit } from 'app/entities/unit/unit.model';
import { UnitService } from 'app/entities/unit/service/unit.service';

@Component({
  standalone: true,
  selector: 'jhi-unit-converter',
  templateUrl: './unit-converter.component.html',
  imports: [
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
    SharedModule,
    SortDirective,
    SortByDirective,
    DurationPipe,
    FormatMediumDatetimePipe,
    FormatMediumDatePipe,
  ],
})
export class UnitConverterComponent implements OnInit {
  subscription: Subscription | null = null;
  unitConverters?: IUnitConverter[];
  isLoading = false;

  sortState = sortStateSignal({});

  unitsSharedCollection: IUnit[] = [];

  public router = inject(Router);
  protected unitService = inject(UnitService);
  protected unitConverterService = inject(UnitConverterService);
  protected unitConverterSearchFormService = inject(UnitConverterSearchFormService);
  protected activatedRoute = inject(ActivatedRoute);
  protected sortService = inject(SortService);
  protected modalService = inject(NgbModal);
  protected ngZone = inject(NgZone);

  searchForm: UnitConverterSearchFormGroup = this.unitConverterSearchFormService.createUnitConverterSearchFormGroup();

  trackId = (_index: number, item: IUnitConverter): number => this.unitConverterService.getEntityIdentifier(item);

  compareUnit = (o1: IUnit | null, o2: IUnit | null): boolean =>
    this.unitService.compareEntity(o1, o2);
    
  ngOnInit(): void {
    this.subscription = combineLatest([this.activatedRoute.queryParamMap, this.activatedRoute.data])
      .pipe(
        tap(([params, data]) => this.fillComponentAttributeFromRoute(params, data)),
        tap(() => {
          if (!this.unitConverters || this.unitConverters.length === 0) {
            this.load();
          }
        }),
      )
      .subscribe();
    
    this.loadRelationshipsOptions();
  }

  delete(unitConverter: IUnitConverter): void {
    const modalRef = this.modalService.open(UnitConverterDeleteDialogComponent, { size: 'lg', backdrop: 'static' });
    modalRef.componentInstance.unitConverter = unitConverter;
    // unsubscribe not needed because closed completes on modal close
    modalRef.closed
      .pipe(
        filter(reason => reason === ITEM_DELETED_EVENT),
        tap(() => this.load()),
      )
      .subscribe();
  }

  onSearch(): void {
	  this.load();
  }
  
  load(): void {
    this.queryBackend().subscribe({
      next: (res: EntityArrayResponseType) => {
        this.onResponseSuccess(res);
      },
    });
  }

  navigateToWithComponentValues(event: SortState): void {
    this.handleNavigation(event);
  }

  protected fillComponentAttributeFromRoute(params: ParamMap, data: Data): void {
    this.sortState.set(this.sortService.parseSortParam(params.get(SORT) ?? data[DEFAULT_SORT_DATA]));
  }

  protected onResponseSuccess(response: EntityArrayResponseType): void {
    const dataFromBody = this.fillComponentAttributesFromResponseBody(response.body);
    this.unitConverters = this.refineData(dataFromBody);
  }

  protected refineData(data: IUnitConverter[]): IUnitConverter[] {
    const { predicate, order } = this.sortState();
    return predicate && order ? data.sort(this.sortService.startSort({ predicate, order })) : data;
  }

  protected fillComponentAttributesFromResponseBody(data: IUnitConverter[] | null): IUnitConverter[] {
    return data ?? [];
  }

  protected queryBackend(): Observable<EntityArrayResponseType> {
    this.isLoading = true;
    const queryObject: any = {
      eagerload: true,
      sort: this.sortService.buildSortParam(this.sortState()),
    };
    
    const searchModel = this.unitConverterSearchFormService.getUnitConverter(this.searchForm);
    this.unitConverterSearchFormService.applySearchConditionsToQueryObject(queryObject, searchModel);
	
    return this.unitConverterService.query(queryObject).pipe(tap(() => (this.isLoading = false)));
  }

  protected handleNavigation(sortState: SortState): void {
    const queryParamsObj = {
      sort: this.sortService.buildSortParam(sortState),
    };

    this.ngZone.run(() => {
      this.router.navigate(['./'], {
        relativeTo: this.activatedRoute,
        queryParams: queryParamsObj,
      });
    });
  }
  
  protected loadRelationshipsOptions(): void {
    this.unitService
      .query()
      .pipe(map((res: HttpResponse<IUnit[]>) => res.body ?? []))
      .subscribe((units: IUnit[]) => (this.unitsSharedCollection = units));
  }
}
