import { Component, inject, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Observable, tap, of } from 'rxjs';
import { finalize, map } from 'rxjs/operators';

import SharedModule from 'app/shared/shared.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { IVariableScope } from 'app/entities/variable-scope/variable-scope.model';
import { VariableScopeService } from 'app/entities/variable-scope/service/variable-scope.service';
import { IVariableCategory } from 'app/entities/variable-category/variable-category.model';
import { VariableCategoryService } from 'app/entities/variable-category/service/variable-category.service';
import { EmissionFactorService } from '../service/emission-factor.service';
import { IEmissionFactor } from '../emission-factor.model';
import { EmissionFactorFormService, EmissionFactorFormGroup } from './emission-factor-form.service';

@Component({
  standalone: true,
  selector: 'jhi-emission-factor-update',
  templateUrl: './emission-factor-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule],
})
export class EmissionFactorUpdateComponent implements OnInit {
  isSaving = false;
  emissionFactor: IEmissionFactor | null = null;

  variableScopesSharedCollection: IVariableScope[] = [];
  variableCategoriesSharedCollection: IVariableCategory[] = [];

  protected emissionFactorService = inject(EmissionFactorService);
  protected emissionFactorFormService = inject(EmissionFactorFormService);
  protected variableScopeService = inject(VariableScopeService);
  protected variableCategoryService = inject(VariableCategoryService);
  protected activatedRoute = inject(ActivatedRoute);

  // eslint-disable-next-line @typescript-eslint/member-ordering
  editForm: EmissionFactorFormGroup = this.emissionFactorFormService.createEmissionFactorFormGroup();

  compareVariableScope = (o1: IVariableScope | null, o2: IVariableScope | null): boolean =>
    this.variableScopeService.compareEntity(o1, o2);

  compareVariableCategory = (o1: IVariableCategory | null, o2: IVariableCategory | null): boolean =>
    this.variableCategoryService.compareEntity(o1, o2);

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ emissionFactor }) => {
      this.emissionFactor = emissionFactor;
      if (emissionFactor) {
        // Is cloning ?
        const lastSegment = this.activatedRoute.snapshot.url[this.activatedRoute.snapshot.url.length - 1]?.path;
        const isCloning = lastSegment === 'clone';
        if (isCloning) {
          // Clear the ID and Version
          emissionFactor.id = null;
          emissionFactor.version = null;
        }
        
        this.updateForm(emissionFactor);
      }

      // Listen to changes to the scope filter property
      this.editForm.get('variableScope')?.valueChanges.subscribe((scope) => {
        this.editForm.get('variableCategory')?.setValue(null);
        this.loadCategoriesOfSelectedScope(scope).subscribe((cats: IVariableCategory[] | null) => {
          if (cats) {
            this.variableCategoriesSharedCollection = cats;
          }
        });
      });
      
      this.loadRelationshipsOptions();
    });
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving = true;
    const emissionFactor = this.emissionFactorFormService.getEmissionFactor(this.editForm);
    if (emissionFactor.id !== null) {
      this.subscribeToSaveResponse(this.emissionFactorService.update(emissionFactor));
    } else {
      this.subscribeToSaveResponse(this.emissionFactorService.create(emissionFactor));
    }
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IEmissionFactor>>): void {
    result.pipe(finalize(() => this.onSaveFinalize())).subscribe({
      next: () => this.onSaveSuccess(),
      error: () => this.onSaveError(),
    });
  }

  protected onSaveSuccess(): void {
    this.previousState();
  }

  protected onSaveError(): void {
    // Api for inheritance.
  }

  protected onSaveFinalize(): void {
    this.isSaving = false;
  }

  protected updateForm(emissionFactor: IEmissionFactor): void {
    this.emissionFactor = emissionFactor;
    this.emissionFactorFormService.resetForm(this.editForm, emissionFactor);

    this.variableScopesSharedCollection = this.variableScopeService.addEntityToCollectionIfMissing<IVariableScope>(
      this.variableScopesSharedCollection,
      emissionFactor.variableScope,
    );
    
    this.loadCategoriesOfSelectedScope(emissionFactor.variableScope).subscribe((cats: IVariableCategory[] | null) => {
      if (cats) {
        this.variableCategoriesSharedCollection = cats;
      }
      
      this.variableCategoriesSharedCollection = this.variableCategoryService.addEntityToCollectionIfMissing<IVariableCategory>(
        this.variableCategoriesSharedCollection,
        emissionFactor.variableCategory,
      );
    });
  }

  protected loadCategoriesOfSelectedScope(scope: IVariableScope|null|undefined): Observable<IVariableCategory[] | null> {
    if (scope) {
      return this.variableCategoryService
              .queryByScopeForFactor(scope.id)
              .pipe(map((res: HttpResponse<IVariableCategory[]>) => res.body ?? []));
    } else {
      return of(null).pipe(
        tap(() => {
          this.variableCategoriesSharedCollection = [];
        })
      );
    }
  }
  
  protected loadRelationshipsOptions(): void {
    this.variableScopeService
      .query()
      .pipe(map((res: HttpResponse<IVariableScope[]>) => res.body ?? []))
      .pipe(
        map((variableScopes: IVariableScope[]) =>
          this.variableScopeService.addEntityToCollectionIfMissing<IVariableScope>(
            variableScopes,
            this.emissionFactor?.variableScope,
          ),
        ),
      )
      .subscribe((variableScopes: IVariableScope[]) => (this.variableScopesSharedCollection = variableScopes));
  }
}
