import { Component, OnInit, inject } from '@angular/core';
import { Observable, tap } from 'rxjs';
import { sortStateSignal, SortDirective, SortByDirective, type SortState, SortService } from 'app/shared/sort';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import SharedModule from 'app/shared/shared.module';

import { ResilientEnvironmentService, EntityArrayResponseType } from 'app/resilient/resilient-environment/service/resilient-environment.service';
import { OrganizationService } from 'app/entities/organization/service/organization.service';
import { IOrganization } from 'app/entities/organization/organization.model';
import { AccountService } from 'app/core/auth/account.service';

@Component({
  selector: 'jhi-resilient-organizations',
  standalone: true,
  imports: [SharedModule,FormsModule, ReactiveFormsModule],
  templateUrl: './resilient-organizations.component.html',
  styleUrl: './resilient-organizations.component.scss'
})
export class ResilientOrganizationsComponent implements OnInit {
  organizations?: IOrganization[];
  selectedOrganization?: IOrganization;
  isLoading = false;
  
  sortState = sortStateSignal({});
  
  protected organizationService = inject(OrganizationService);
  protected environmentService = inject(ResilientEnvironmentService);
  protected sortService = inject(SortService);
  protected accountService = inject(AccountService);
  
 compareOrganization = (o1: IOrganization | null, o2: IOrganization | null): boolean =>
    this.organizationService.compareEntity(o1, o2);

  ngOnInit(): void {
    if (!this.organizations || this.organizations.length === 0) {
      this.load();
    }
  }
  
  load(): void {
    this.queryBackend().subscribe({
      next: (res: EntityArrayResponseType) => {
        this.onResponseSuccess(res);
      },
    });
  }
  
  onChange(event: any): void {
    this.environmentService.selectWorkOrganization(this.selectedOrganization??null);
  }
  
  protected queryBackend(): Observable<EntityArrayResponseType> {
    this.isLoading = true;
    const queryObject: any = {
      eagerload: true,
      sort: this.sortService.buildSortParam(this.sortState()),
    };
    return this.environmentService.organizations(queryObject).pipe(tap(() => (this.isLoading = false)));
  }
  
  protected onResponseSuccess(response: EntityArrayResponseType): void {
    const dataFromBody = this.fillComponentAttributesFromResponseBody(response.body);
    this.organizations = this.refineData(dataFromBody);
    
    if (this.organizations.length >= 1) {
      
      const parent: IOrganization | null = this.accountService.getParentOrganization();
      if (parent) {
        // Select the user Parent Organization
        this.selectedOrganization = this.organizations.find(org => org.id === parent.id);
        if (this.selectedOrganization) {
          this.environmentService.selectWorkOrganization(this.selectedOrganization);
        }
      } else {
        // Select the first
        this.selectedOrganization = this.organizations[0]; 
        this.environmentService.selectWorkOrganization(this.selectedOrganization);
      }

    }
  }
  
  protected refineData(data: IOrganization[]): IOrganization[] {
    const { predicate, order } = this.sortState();
    return predicate && order ? data.sort(this.sortService.startSort({ predicate, order })) : data;
  }
  
  protected fillComponentAttributesFromResponseBody(data: IOrganization[] | null): IOrganization[] {
    return data ?? [];
  }
}
