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

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

import { IVariableScope } from '../variable-scope.model';
import { VariableScopeService } from '../service/variable-scope.service';
import { VariableScopeFormService, VariableScopeFormGroup } from './variable-scope-form.service';

@Component({
  standalone: true,
  selector: 'jhi-variable-scope-update',
  templateUrl: './variable-scope-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule],
})
export class VariableScopeUpdateComponent implements OnInit {
  isSaving = false;
  variableScope: IVariableScope | null = null;

  protected variableScopeService = inject(VariableScopeService);
  protected variableScopeFormService = inject(VariableScopeFormService);
  protected activatedRoute = inject(ActivatedRoute);

  // eslint-disable-next-line @typescript-eslint/member-ordering
  editForm: VariableScopeFormGroup = this.variableScopeFormService.createVariableScopeFormGroup();

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ variableScope }) => {
      this.variableScope = variableScope;
      if (variableScope) {
        this.updateForm(variableScope);
      }
    });
  }

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

  save(): void {
    this.isSaving = true;
    const variableScope = this.variableScopeFormService.getVariableScope(this.editForm);
    if (variableScope.id !== null) {
      this.subscribeToSaveResponse(this.variableScopeService.update(variableScope));
    } else {
      this.subscribeToSaveResponse(this.variableScopeService.create(variableScope));
    }
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IVariableScope>>): 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(variableScope: IVariableScope): void {
    this.variableScope = variableScope;
    this.variableScopeFormService.resetForm(this.editForm, variableScope);
  }
}
