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

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

import { IOrganizationType } from 'app/entities/organization-type/organization-type.model';
import { OrganizationTypeService } from 'app/entities/organization-type/service/organization-type.service';
import { MetadataType } from 'app/entities/enumerations/metadata-type.model';
import { MetadataPropertyService } from '../service/metadata-property.service';
import { IMetadataProperty } from '../metadata-property.model';
import { MetadataPropertyFormService, MetadataPropertyFormGroup } from './metadata-property-form.service';

@Component({
  standalone: true,
  selector: 'jhi-metadata-property-update',
  templateUrl: './metadata-property-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule],
})
export class MetadataPropertyUpdateComponent implements OnInit {
  isSaving = false;
  metadataProperty: IMetadataProperty | null = null;
  metadataTypeValues = Object.keys(MetadataType);

  organizationTypesSharedCollection: IOrganizationType[] = [];

  protected metadataPropertyService = inject(MetadataPropertyService);
  protected metadataPropertyFormService = inject(MetadataPropertyFormService);
  protected organizationTypeService = inject(OrganizationTypeService);
  protected activatedRoute = inject(ActivatedRoute);

  // eslint-disable-next-line @typescript-eslint/member-ordering
  editForm: MetadataPropertyFormGroup = this.metadataPropertyFormService.createMetadataPropertyFormGroup();

  compareOrganizationType = (o1: IOrganizationType | null, o2: IOrganizationType | null): boolean =>
    this.organizationTypeService.compareEntity(o1, o2);

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

      this.loadRelationshipsOptions();
    });
  }

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

  save(): void {
    this.isSaving = true;
    const metadataProperty = this.metadataPropertyFormService.getMetadataProperty(this.editForm);
    if (metadataProperty.id !== null) {
      this.subscribeToSaveResponse(this.metadataPropertyService.update(metadataProperty));
    } else {
      this.subscribeToSaveResponse(this.metadataPropertyService.create(metadataProperty));
    }
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IMetadataProperty>>): 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(metadataProperty: IMetadataProperty): void {
    this.metadataProperty = metadataProperty;
    this.metadataPropertyFormService.resetForm(this.editForm, metadataProperty);

    this.organizationTypesSharedCollection = this.organizationTypeService.addEntityToCollectionIfMissing<IOrganizationType>(
      this.organizationTypesSharedCollection,
      ...(metadataProperty.organizationTypes ?? []),
    );
  }

  protected loadRelationshipsOptions(): void {
    this.organizationTypeService
      .query()
      .pipe(map((res: HttpResponse<IOrganizationType[]>) => res.body ?? []))
      .pipe(
        map((organizationTypes: IOrganizationType[]) =>
          this.organizationTypeService.addEntityToCollectionIfMissing<IOrganizationType>(
            organizationTypes,
            ...(this.metadataProperty?.organizationTypes ?? []),
          ),
        ),
      )
      .subscribe((organizationTypes: IOrganizationType[]) => (this.organizationTypesSharedCollection = organizationTypes));
  }
}
