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

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 { IInputData, NewInputData } from '../input-data.model';
import { IPeriod } from 'app/entities/period/period.model';
import { IOrganization } from 'app/entities/organization/organization.model';
import { IVariableScope } from 'app/entities/variable-scope/variable-scope.model';
import { IVariableCategory } from 'app/entities/variable-category/variable-category.model';
import { PeriodService } from 'app/entities/period/service/period.service';
import { OrganizationService } from 'app/entities/organization/service/organization.service';
import { VariableScopeService } from 'app/entities/variable-scope/service/variable-scope.service';
import { VariableCategoryService } from 'app/entities/variable-category/service/variable-category.service';
import { EntityArrayResponseType, InputDataService } from '../service/input-data.service';
import { InputDataDeleteDialogComponent } from '../delete/input-data-delete-dialog.component';
import { InputDataSearchFormService, InputDataSearchFormGroup } from './input-data-search-form.service';
import { ResilientEnvironmentService } from 'app/resilient/resilient-environment/service/resilient-environment.service';
import { AbstractResilientEntityComponent } from 'app/entities/resilient/resilient-entity.component';

@Component({
  standalone: true,
  selector: 'jhi-input-data',
  templateUrl: './input-data.component.html',
  styleUrl: './input-data.component.css',
  imports: [
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
    SharedModule,
    SortDirective,
    SortByDirective,
    DurationPipe,
    FormatMediumDatetimePipe,
    FormatMediumDatePipe,
    MatProgressSpinnerModule,
  ],
})
export class InputDataComponent extends AbstractResilientEntityComponent<IInputData, NewInputData, InputDataService> implements OnInit {
  subscriptionWorkOrganization!: Subscription;  // Store the subscription
  selectedOrganization?: IOrganization;
  subscription: Subscription | null = null;
  inputData?: IInputData[];
  isLoading = false;
  isExporting: boolean = false;

  sortState = sortStateSignal({});

  scopesSharedCollection: IVariableScope[] = [];
  categoriesSharedCollection: IVariableCategory[] = [];
  periodsSharedCollection: IPeriod[] = [];
  orgsSharedCollection: IOrganization[] = [];

  public router = inject(Router);
  protected variableScopeService = inject(VariableScopeService);
  protected variableCategoryService = inject(VariableCategoryService);
  protected periodService = inject(PeriodService);
  protected organizationService = inject(OrganizationService);
  protected inputDataService = inject(InputDataService);
  protected inputDataSearchFormService = inject(InputDataSearchFormService);
  protected activatedRoute = inject(ActivatedRoute);
  protected sortService = inject(SortService);
  protected modalService = inject(NgbModal);
  protected ngZone = inject(NgZone);
  protected envService = inject(ResilientEnvironmentService);

  searchForm: InputDataSearchFormGroup = this.inputDataSearchFormService.createInputDataSearchFormGroup();
  trackId = (_index: number, item: IInputData): number => this.inputDataService.getEntityIdentifier(item);

  comparePeriod = (o1: IPeriod | null, o2: IPeriod | null): boolean =>
    this.periodService.compareEntity(o1, o2);

  compareOrganization = (o1: IOrganization | null, o2: IOrganization | null): boolean =>
    this.organizationService.compareEntity(o1, o2);
    
  compareScope = (o1: IVariableScope | null, o2: IVariableScope | null): boolean =>
    this.variableScopeService.compareEntity(o1, o2);

  compareCategory = (o1: IVariableCategory | null, o2: IVariableCategory | null): boolean =>
    this.variableCategoryService.compareEntity(o1, o2);
  
  constructor(service: InputDataService) { super(service); }

  ngOnInit(): void {
    // Get the currently selected ORGANIZATION, by ResilientEnvironmentService
    this.subscriptionWorkOrganization = this
      .envService
      .selectedWorkOrganization
      /* .pipe(first())		// READS the Observable only once. Doesn't react to later changes on the subscription */
      .subscribe(org => {
        if(org){
          this.selectedOrganization = org;
          
          // Set filter
          this.searchForm.get('ownerId')?.setValue(org.id);
          
          // Clear list
          this.inputData = undefined;
          
          // Execute search
          if (this.searchForm.valid) {
            this.load();
          }
        }
      });
      
    // Listen to changes to the scope filter property
    this.searchForm.get('variableScopeId')?.valueChanges.subscribe((scopeId) => {
      this.loadCategoriesOfSelectedScope(scopeId);
      this.searchForm.get('variableCategoryId')?.setValue(null);
    });
    
    this.loadRelationshipsOptions().subscribe(() => {    
      this.subscription = combineLatest([this.activatedRoute.queryParamMap, this.activatedRoute.data])
      .pipe(
        tap(([params, data]) => this.fillComponentAttributeFromRoute(params, data)),
        tap(() => {
          if (!this.inputData || this.inputData.length === 0) {
            this.load();
          }
        }),
      )
      .subscribe();
    });	
  }

  delete(inputData: IInputData): void {
    const modalRef = this.modalService.open(InputDataDeleteDialogComponent, { size: 'lg', backdrop: 'static' });
    modalRef.componentInstance.inputData = inputData;
    // 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.inputData = this.refineData(dataFromBody); */
    this.inputData = dataFromBody;
  }

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

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

  protected queryBackend(): Observable<EntityArrayResponseType> {
    
    this.isLoading = true;
    const queryObject: any = {
      eagerload: true,
    };
	
    const searchModel = this.inputDataSearchFormService.getInputData(this.searchForm);
    if (searchModel) {
      // Apply conditions
      this.inputDataSearchFormService.applySearchConditionsToQueryObject(queryObject, searchModel);    
    }
  
    return this.inputDataService.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,
      });
    });
  }
  
  onPeriodChange(event: Event) {
    const selectedValue = (event.target as HTMLSelectElement).value;
    this.searchForm.get('periodId')?.setValue(Number(selectedValue));
  }

  protected loadRelationshipsOptions(): Observable<void> {
    return new Observable<void>((observer) => {
      this.periodService
      .query()
      .pipe(map((res: HttpResponse<IPeriod[]>) => res.body ?? []))
      .subscribe((periods: IPeriod[]) => { 
        this.periodsSharedCollection = periods;
        
        // Set first Period as default. It's mandatory to select a Period
        this.searchForm.get('periodId')?.setValue(this.periodsSharedCollection[0]?.id);

        observer.next(); // Notify that process is complete
        observer.complete();
      });

      this.variableScopeService
        .queryForData()
        .pipe(map((res: HttpResponse<IVariableScope[]>) => res.body ?? []))
        .subscribe((scopes: IVariableScope[]) => (this.scopesSharedCollection = scopes));
      
      
      this.organizationService
        .query()
        .pipe(map((res: HttpResponse<IOrganization[]>) => res.body ?? []))
        .subscribe((orgs: IOrganization[]) => (this.orgsSharedCollection = orgs));
  
    });
  }
  
  protected loadCategoriesOfSelectedScope(scopeId: number|null|undefined): void {
    if (scopeId) {
      this.variableCategoryService
          .queryByScopeForData(scopeId)
          .pipe(map((res: HttpResponse<IVariableCategory[]>) => res.body ?? []))
          .subscribe((cats: IVariableCategory[]) => (this.categoriesSharedCollection = cats));
    } else {
      this.categoriesSharedCollection = [];
    }
  }

  export(): void {
    this.isExporting = true;
    const periodId = this.searchForm.get('periodId')?.value;

    this.inputDataService.export(periodId!).subscribe((blob: Blob) => {
      const a = document.createElement('a');
      const objectUrl = URL.createObjectURL(blob);
      a.href = objectUrl;
      a.download = 'report.xlsx';
      a.click();
      URL.revokeObjectURL(objectUrl);

      this.isExporting = false;
    });
  }
}
