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

import SharedModule from 'app/shared/shared.module';
import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date';
import { IResilientLog } from '../resilient-log.model';
import { EntityArrayResponseType, ResilientLogService } from '../service/resilient-log.service';

@Component({
  standalone: true,
  templateUrl: './resilient-log-logs-dialog.component.html',
  styleUrl: './resilient-log-logs-dialog.component.css',
  imports: [
	SharedModule, 
	FormsModule,
	SortDirective,
    SortByDirective,
    DurationPipe,
    FormatMediumDatetimePipe,
    FormatMediumDatePipe,
  ],
})
export class ResilientLogLogsDialogComponent implements OnInit {
  ownerId?: number;
  resilientLogs?: IResilientLog[];
  isLoading = false;

  sortState = sortStateSignal({});

  protected sortService = inject(SortService);
  protected resilientLogService = inject(ResilientLogService);
  protected activeModal = inject(NgbActiveModal);

  trackId = (_index: number, item: IResilientLog): number => this.resilientLogService.getEntityIdentifier(item);

  setOwnerId(ownerId: number) {
    this.ownerId = ownerId;
  }

  ngOnInit(): void {
	if (this.ownerId) {
		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.resilientLogs = this.refineData(dataFromBody);
  }
  
  protected refineData(data: IResilientLog[]): IResilientLog[] {
    const { predicate, order } = this.sortState();
    return predicate && order ? data.sort(this.sortService.startSort({ predicate, order })) : data;
  }

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

    return this.resilientLogService.findByOwner(this.ownerId ?? 0).pipe(tap(() => (this.isLoading = false)));
  
  }
}
