import { Component, inject, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { sortStateSignal, SortDirective, SortByDirective, type SortState, SortService } from 'app/shared/sort';
import { combineLatest, filter, Observable, Subscription, tap } from 'rxjs';

import SharedModule from 'app/shared/shared.module';
import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date';
import { ITEM_DELETED_EVENT } from 'app/config/navigation.constants';
import { IInputDataUpload } from 'app/entities/input-data-upload/input-data-upload.model';
import { IInputDataUploadLog } from '../input-data-upload-log.model';
import { EntityArrayResponseType, InputDataUploadLogService } from '../service/input-data-upload-log.service';

@Component({
  standalone: true,
  templateUrl: './input-data-upload-log-logs-dialog.component.html',
  styleUrl: './input-data-upload-log-logs-dialog.component.css',
  imports: [
	SharedModule, 
	FormsModule,
	SortDirective,
    SortByDirective,
    DurationPipe,
    FormatMediumDatetimePipe,
    FormatMediumDatePipe,
  ],
})
export class InputDataUploadLogLogsDialogComponent implements OnInit {
  inputDataUpload?: IInputDataUpload;
  inputDataUploadLogs?: IInputDataUploadLog[];
  isLoading = false;

  sortState = sortStateSignal({});

  protected sortService = inject(SortService);
  protected inputDataUploadLogService = inject(InputDataUploadLogService);
  protected activeModal = inject(NgbActiveModal);

  trackId = (_index: number, item: IInputDataUploadLog): number => this.inputDataUploadLogService.getEntityIdentifier(item);

  setInputDataUpload(inputDataUpload: IInputDataUpload) {
    this.inputDataUpload = inputDataUpload;
  }

  ngOnInit(): void {
	if (this.inputDataUpload) {
		this.load();
	}
  }
  
  cancel(): void {
    this.activeModal.dismiss();
  }
  
  load(): void {
    this.queryBackend().subscribe({
      next: (res: EntityArrayResponseType) => {
        this.onResponseSuccess(res);
      },
    });
  }
  
  protected onResponseSuccess(response: EntityArrayResponseType): void {
    const dataFromBody = this.fillComponentAttributesFromResponseBody(response.body);
    this.inputDataUploadLogs = this.refineData(dataFromBody);
  }
  
  protected refineData(data: IInputDataUploadLog[]): IInputDataUploadLog[] {
    const { predicate, order } = this.sortState();
    return predicate && order ? data.sort(this.sortService.startSort({ predicate, order })) : data;
  }

  protected fillComponentAttributesFromResponseBody(data: IInputDataUploadLog[] | null): IInputDataUploadLog[] {
    return data ?? [];
  }
  
  protected queryBackend(): Observable<EntityArrayResponseType> {
    this.isLoading = true;

    return this.inputDataUploadLogService.findByOwner(this.inputDataUpload?.id ?? 0).pipe(tap(() => (this.isLoading = false)));
  
  }
}
