import { Component, Input, OnInit, inject, EventEmitter, Output } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap';
import { combineLatest, filter, Observable, Subscription, tap, map } from 'rxjs';
import { HttpResponse } from '@angular/common/http';

import { IOrganization } from '../../organization.model';
import { OrganizationTypeService } from 'app/entities/organization-type/service/organization-type.service';
import { IOrganizationType } from 'app/entities/organization-type/organization-type.model';

interface TreeOption {
 title: string;
 routerLink: string[];
 queryParams: {};
}

interface TreeNode {
 expandable: boolean;
 name: string;
 id: number;
 level: number;
 org: IOrganization;
}

@Component({
  selector: 'organization-tree-actions',
  standalone: true,
  imports: [RouterModule,CommonModule,FontAwesomeModule,NgbDropdownModule,],
  templateUrl: './organization-tree-actions.component.html',
  styleUrl: './organization-tree-actions.component.css'
})
export class OrganizationTreeActionsComponent implements OnInit {
  // Input properties
  @Input() node: any;
  
  // Evento emitter (for parent reaction)
  @Output() actionDeletedEvent = new EventEmitter<{organization: IOrganization}>();
  
  options: TreeOption[] = [];	// List of options for this component instance
  isDeleteDisabled: boolean = true;  // Delete Action is initially disabled
  
  protected organizationTypeService = inject(OrganizationTypeService);
  
  ngOnInit(): void {
	this.loadOptions();
	
	if (this.node.expandable) {
	  this.isDeleteDisabled = true;
	} else {
	  this.isDeleteDisabled = false;
	}
  }
  
  loadOptions(): void {
    this.organizationTypeService
      .queryByNature(this.node.org.organizationType.nature)
      .pipe(map((res: HttpResponse<IOrganizationType[]>) => res.body ?? []))
      .subscribe({
        next: (res: IOrganizationType[]) => {
          this.onResponseSuccess(res);
        },
	  });
  }
  
  delete(organization: IOrganization): void {
    this.actionDeletedEvent.emit({organization});	// {organization: organization} is the same as {organization}. Its called a "Literal Shorthand Syntax", when the key name matches the name of the variable
  }
  
  protected onResponseSuccess(res: IOrganizationType[]): void {
	for (const r of res) {
		this.options.push({
			title: r.name?r.name:"",
			routerLink: ["/organization", 'new'],
			queryParams: {parentOrganizationId:this.node.org.id, organizationTypeId:r.id},
		});
	}
  }
}
