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 { MatProgressSpinnerModule } from '@angular/material/progress-spinner';

import SharedModule from 'app/shared/shared.module';
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 { IInventory } from '../inventory.model';
import { IPeriod } from 'app/entities/period/period.model';
import { IVariableScope } from 'app/entities/variable-scope/variable-scope.model';
import { IVariableCategory } from 'app/entities/variable-category/variable-category.model';
import { IOrganization } from 'app/entities/organization/organization.model';
import { PeriodService } from 'app/entities/period/service/period.service';
import { VariableScopeService } from 'app/entities/variable-scope/service/variable-scope.service';
import { VariableCategoryService } from 'app/entities/variable-category/service/variable-category.service';
import { OrganizationService } from 'app/entities/organization/service/organization.service';
import { EntityArrayResponseType, InventoryService } from '../service/inventory.service';
import { InventorySearchFormService, InventorySearchFormGroup } from './inventory-search-form.service';
import { ResilientEnvironmentService } from 'app/resilient/resilient-environment/service/resilient-environment.service';
import { FormatHelper } from 'app/shared/utils/format-helper';

@Component({
  standalone: true,
  selector: 'jhi-inventory',
  templateUrl: './inventory.component.html',
  styleUrl: './inventory.component.css',
  imports: [
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
    SharedModule,
    DurationPipe,
    FormatMediumDatetimePipe,
    FormatMediumDatePipe,
    MatProgressSpinnerModule,
  ],
})
export class InventoryComponent implements OnInit {
  subscriptionWorkOrganization!: Subscription;  // Store the subscription
  subscription: Subscription | null = null;
  inventory?: IInventory[];
  isLoading = false;
  isExporting: boolean = false;

  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 inventoryService = inject(InventoryService);
  protected inventorySearchFormService = inject(InventorySearchFormService);
  protected activatedRoute = inject(ActivatedRoute);
  protected modalService = inject(NgbModal);
  protected ngZone = inject(NgZone);
  protected envService = inject(ResilientEnvironmentService);

  searchForm: InventorySearchFormGroup = this.inventorySearchFormService.createInventorySearchFormGroup();
  trackId = (_index: number, item: IInventory): number => this.inventoryService.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);
    
  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){
          // Set filter
          this.searchForm.get('ownerId')?.setValue(org.id);
          
          // Clear list
          this.inventory = undefined;
          
          // Execute search
          if (this.searchForm.valid) {
            this.load();
          }
        }
      });
    
    // Listen to changes to the scope filter property
    this.searchForm.get('scopeId')?.valueChanges.subscribe((scopeId) => {
      this.loadCategoriesOfSelectedScope(scopeId);
      this.searchForm.get('categoryId')?.setValue(null);
    });
    
    this.loadRelationshipsOptions();
  }

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

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

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

  protected queryBackend(): Observable<EntityArrayResponseType> {
    this.isLoading = true;
    const queryObject: any = {
      eagerload: true,
    };
	
    const searchModel = this.inventorySearchFormService.getInventory(this.searchForm);
    this.inventorySearchFormService.applySearchConditionsToQueryObject(queryObject, searchModel);
	
    return this.inventoryService.query(queryObject).pipe(tap(() => (this.isLoading = false)));
  }
  
  protected loadRelationshipsOptions(): void {
    this.variableScopeService
      .queryForData()
      .pipe(map((res: HttpResponse<IVariableScope[]>) => res.body ?? []))
      .subscribe((scopes: IVariableScope[]) => (this.scopesSharedCollection = scopes));
    
    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);
      });
  
    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 = [];
    }
  }
  
  formatValue(value: number): string {
    return FormatHelper.formatDecimalValue(value);
  }

  export(): void {
    this.isExporting = true;
    const queryObject: any = {
      eagerload: true,
    };
	
    const searchModel = this.inventorySearchFormService.getInventory(this.searchForm);
    if (searchModel) {
      // Apply conditions
      this.inventorySearchFormService.applySearchConditionsToQueryObject(queryObject, searchModel);    
    }

    this.inventoryService.export(queryObject).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;
    });
  }
}
