import { Component, inject, OnInit, ElementRef } 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 { AlertError } from 'app/shared/alert/alert-error.model';
import { EventManager, EventWithContent } from 'app/core/util/event-manager.service';
import { DataUtils, FileLoadError } from 'app/core/util/data-util.service';
import { IMetadataProperty } from 'app/entities/metadata-property/metadata-property.model';
import { MetadataPropertyService } from 'app/entities/metadata-property/service/metadata-property.service';
import { OrganizationNature } from 'app/entities/enumerations/organization-nature.model';
import { OrganizationTypeService } from '../service/organization-type.service';
import { IOrganizationType } from '../organization-type.model';
import { OrganizationTypeFormService, OrganizationTypeFormGroup } from './organization-type-form.service';

@Component({
  standalone: true,
  selector: 'jhi-organization-type-update',
  templateUrl: './organization-type-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule],
})
export class OrganizationTypeUpdateComponent implements OnInit {
  isSaving = false;
  organizationType: IOrganizationType | null = null;
  organizationNatureValues = Object.keys(OrganizationNature);

  metadataPropertiesSharedCollection: IMetadataProperty[] = [];

  protected dataUtils = inject(DataUtils);
  protected eventManager = inject(EventManager);
  protected organizationTypeService = inject(OrganizationTypeService);
  protected organizationTypeFormService = inject(OrganizationTypeFormService);
  protected metadataPropertyService = inject(MetadataPropertyService);
  protected elementRef = inject(ElementRef);
  protected activatedRoute = inject(ActivatedRoute);

  // eslint-disable-next-line @typescript-eslint/member-ordering
  editForm: OrganizationTypeFormGroup = this.organizationTypeFormService.createOrganizationTypeFormGroup();

  compareMetadataProperty = (o1: IMetadataProperty | null, o2: IMetadataProperty | null): boolean =>
    this.metadataPropertyService.compareEntity(o1, o2);

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

      this.loadRelationshipsOptions();
    });
  }

  byteSize(base64String: string): string {
    return this.dataUtils.byteSize(base64String);
  }

  openFile(base64String: string, contentType: string | null | undefined): void {
    this.dataUtils.openFile(base64String, contentType);
  }

  setFileData(event: Event, field: string, isImage: boolean): void {
    this.dataUtils.loadFileToForm(event, this.editForm, field, isImage).subscribe({
      error: (err: FileLoadError) =>
        this.eventManager.broadcast(new EventWithContent<AlertError>('resilientApp.error', { ...err, key: 'error.file.' + err.key })),
    });
  }

  clearInputImage(field: string, fieldContentType: string, idInput: string): void {
    this.editForm.patchValue({
      [field]: null,
      [fieldContentType]: null,
    });
    if (idInput && this.elementRef.nativeElement.querySelector('#' + idInput)) {
      this.elementRef.nativeElement.querySelector('#' + idInput).value = null;
    }
  }

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

  save(): void {
    this.isSaving = true;
    const organizationType = this.organizationTypeFormService.getOrganizationType(this.editForm);
    if (organizationType.id !== null) {
      this.subscribeToSaveResponse(this.organizationTypeService.update(organizationType));
    } else {
      this.subscribeToSaveResponse(this.organizationTypeService.create(organizationType));
    }
  }

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

    this.metadataPropertiesSharedCollection = this.metadataPropertyService.addEntityToCollectionIfMissing<IMetadataProperty>(
      this.metadataPropertiesSharedCollection,
      ...(organizationType.metadataProperties ?? []),
    );
  }

  protected loadRelationshipsOptions(): void {
    this.metadataPropertyService
      .query()
      .pipe(map((res: HttpResponse<IMetadataProperty[]>) => res.body ?? []))
      .pipe(
        map((metadataProperties: IMetadataProperty[]) =>
          this.metadataPropertyService.addEntityToCollectionIfMissing<IMetadataProperty>(
            metadataProperties,
            ...(this.organizationType?.metadataProperties ?? []),
          ),
        ),
      )
      .subscribe((metadataProperties: IMetadataProperty[]) => (this.metadataPropertiesSharedCollection = metadataProperties));
  }
}
