import { Component, Inject, OnInit } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { HttpClient } from '@angular/common/http'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-execute-command', templateUrl: './execute-command.component.html', styleUrls: ['./execute-command.component.css'] }) export class ExecuteCommandComponent implements OnInit { form: FormGroup; units: any[] = []; childUnits: any[] = []; clients: any[] = []; selectedClients: any[] = []; baseUrl: string = import.meta.env.NG_APP_BASE_API_URL; constructor( private dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: any, private http: HttpClient, private fb: FormBuilder ) { this.form = this.fb.group({ unit: [null], childUnit: [null], clientSelection: [[]] }); } ngOnInit(): void { this.loadUnits(); this.form.get('unit')?.valueChanges.subscribe(value => this.onUnitChange(value)); this.form.get('childUnit')?.valueChanges.subscribe(value => this.onChildUnitChange(value)); } loadUnits(): void { this.http.get(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=30`).subscribe( response => { this.units = response['hydra:member'].filter((unit: { type: string; }) => unit.type === 'organizational-unit'); }, error => console.error('Error fetching organizational units:', error) ); } onUnitChange(unitId: string): void { const unit = this.units.find(unit => unit.uuid === unitId); this.childUnits = unit ? this.getAllChildren(unit) : []; this.clients = []; this.form.patchValue({ childUnit: null, clientSelection: [] }); } getAllChildren(unit: any): any[] { let allChildren = []; if (unit.children && unit.children.length > 0) { for (const child of unit.children) { allChildren.push(child); allChildren = allChildren.concat(this.getAllChildren(child)); } } return allChildren; } onChildUnitChange(childUnitId: string): void { const childUnit = this.childUnits.find(unit => unit.uuid === childUnitId); this.clients = childUnit && childUnit.clients ? childUnit.clients : []; this.form.patchValue({ clientSelection: [] }); } executeCommand(): void { const payload = { clients: ['/clients/'+this.form.get('clientSelection')?.value] }; this.http.post(`${this.baseUrl}/commands/${this.data.commandData.uuid}/execute`, payload) .subscribe({ next: () => { console.log('Comando ejecutado con éxito'); this.dialogRef.close(true); }, error: (error) => { console.error('Error al ejecutar el comando:', error); } }); } closeModal(): void { this.dialogRef.close(false); } toggleClientSelection(clientId: string): void { const selectedClients = this.form.get('clientSelection')?.value; if (selectedClients.includes(clientId)) { this.form.get('clientSelection')?.setValue(selectedClients.filter((id: string) => id !== clientId)); } else { this.form.get('clientSelection')?.setValue([...selectedClients, clientId]); } } }