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 { ResilientBaseComponent } from 'app/resilient/resilient-base/resilient-base.component';

import { UnitValueType } from 'app/entities/enumerations/unit-value-type.model';
import { IUnitType } from '../unit-type.model';
import { UnitTypeService } from '../service/unit-type.service';
import { UnitTypeFormService, UnitTypeFormGroup } from './unit-type-form.service';

@Component({
  standalone: true,
  selector: 'jhi-unit-type-update',
  templateUrl: './unit-type-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule],
})
export class UnitTypeUpdateComponent extends ResilientBaseComponent implements OnInit {
  isSaving = false;
  unitType: IUnitType | null = null;
  unitValueTypeValues = Object.keys(UnitValueType);

  protected unitTypeService = inject(UnitTypeService);
  protected unitTypeFormService = inject(UnitTypeFormService);
  protected activatedRoute = inject(ActivatedRoute);

  // eslint-disable-next-line @typescript-eslint/member-ordering
  editForm: UnitTypeFormGroup = this.unitTypeFormService.createUnitTypeFormGroup();

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

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

  save(): void {
    this.isSaving = true;
    const unitType = this.unitTypeFormService.getUnitType(this.editForm);
    if (unitType.id !== null) {
      this.subscribeToSaveResponse(this.unitTypeService.update(unitType));
    } else {
      this.subscribeToSaveResponse(this.unitTypeService.create(unitType));
    }
  }

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