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 { IMetadataValue } from '../metadata-value.model';
import { MetadataValueService } from '../service/metadata-value.service';
import { MetadataValueFormService, MetadataValueFormGroup } from './metadata-value-form.service';

@Component({
  standalone: true,
  selector: 'jhi-metadata-value-update',
  templateUrl: './metadata-value-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule],
})
export class MetadataValueUpdateComponent implements OnInit {
  isSaving = false;
  metadataValue: IMetadataValue | null = null;

  protected metadataValueService = inject(MetadataValueService);
  protected metadataValueFormService = inject(MetadataValueFormService);
  protected activatedRoute = inject(ActivatedRoute);

  // eslint-disable-next-line @typescript-eslint/member-ordering
  editForm: MetadataValueFormGroup = this.metadataValueFormService.createMetadataValueFormGroup();

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

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

  save(): void {
    this.isSaving = true;
    const metadataValue = this.metadataValueFormService.getMetadataValue(this.editForm);
    if (metadataValue.id !== null) {
      this.subscribeToSaveResponse(this.metadataValueService.update(metadataValue));
    } else {
      this.subscribeToSaveResponse(this.metadataValueService.create(metadataValue));
    }
  }

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