import { Component, signal } from '@angular/core'; import { MatTableDataSource } from "@angular/material/table"; import { DatePipe } from "@angular/common"; import { MatDialog } from "@angular/material/dialog"; import { HttpClient } from "@angular/common/http"; import { ToastrService } from "ngx-toastr"; import { DeleteModalComponent } from "../../shared/delete_modal/delete-modal/delete-modal.component"; import { PageEvent } from "@angular/material/paginator"; import { JoyrideService } from 'ngx-joyride'; import { ConfigService } from '@services/config.service'; import { HardwareProfileService } from './hardware-profile.service'; import { HardwareCollectionModalComponent } from './hardware-collection-modal/hardware-collection-modal.component'; import { map, Observable, startWith } from 'rxjs'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-hardware-profile', templateUrl: './hardware-profile.component.html', styleUrl: './hardware-profile.component.css' }) export class HardwareProfileComponent { baseUrl: string; private apiUrl: string; dataSource = new MatTableDataSource(); length: number = 0; itemsPerPage: number = 10; page: number = 0; pageSizeOptions: number[] = [5, 10, 20, 40, 100]; loading: boolean = false; filters: { [key: string]: string } = {}; alertMessage: string | null = null; readonly panelOpenState = signal(false); datePipe: DatePipe = new DatePipe('es-ES'); filteredClients!: Observable; clientControl = new FormControl(); clients: any[] = []; columns = [ { columnDef: 'id', header: 'ID', cell: (hardware: any) => `${hardware.id}`, }, { columnDef: 'description', header: 'Descripción', cell: (hardware: any) => hardware.description }, { columnDef: 'client', header: 'Cliente', cell: (hardware: any) => hardware.client ? { name: hardware.client.name || 'N/A', ip: hardware.client.ip || 'N/A', mac: hardware.client.mac || 'N/A' } : 'N/A' }, { columnDef: 'createdAt', header: 'Fecha de creación', cell: (hardware: any) => `${this.datePipe.transform(hardware.createdAt, 'dd/MM/yyyy hh:mm:ss')}`, } ]; displayedColumns = [...this.columns.map(column => column.columnDef), 'actions']; constructor( public dialog: MatDialog, private http: HttpClient, private toastService: ToastrService, private joyrideService: JoyrideService, private configService: ConfigService, private hardwareProfileService: HardwareProfileService ) { this.baseUrl = this.configService.apiUrl; this.apiUrl = `${this.baseUrl}/hardware-profiles`; } ngOnInit(): void { this.search(); this.loadClients(); this.filteredClients = this.clientControl.valueChanges.pipe( startWith(''), map(value => (typeof value === 'string' ? value : value?.name)), map(name => (name ? this._filterClients(name) : this.clients.slice())) ); } search(): void { this.http.get(`${this.apiUrl}?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe( (data) => { this.dataSource.data = data['hydra:member']; this.length = data['hydra:totalItems']; }, (error) => { console.error('Error fetching commands', error); } ); } displayFnClient(client: any): string { return client && client.name ? client.name : ''; } onOptionClientSelected(selectedClient: any): void { this.filters['client.id'] = selectedClient.id; this.search(); } clearClientFilter(event: Event, clientSearchClientInput: any): void { clientSearchClientInput.value = ''; this.filters['client.id'] = ''; this.search(); } private _filterClients(value: string): any[] { const filterValue = value.toLowerCase(); return this.clients.filter(client => client.name?.toLowerCase().includes(filterValue) || client.ip?.toLowerCase().includes(filterValue) || client.mac?.toLowerCase().includes(filterValue) ); } loadClients() { this.http.get(`${this.baseUrl}/clients`).subscribe( (data) => { this.clients = data['hydra:member']; } ); } deleteHardware(hardware: any): void { const dialogRef = this.dialog.open(DeleteModalComponent, { width: '400px', data: { name: hardware.name } }); dialogRef.afterClosed().subscribe(result => { if (result) { const apiUrl = `${this.baseUrl}${hardware['@id']}`; this.http.delete(apiUrl).subscribe({ next: () => { this.search(); this.toastService.success('Hardware deleted successfully'); }, error: (error) => { this.toastService.error('Error deleting hardware'); } }); } else { console.log('hardware deletion cancelled'); } }); } onPageChange(event: PageEvent) { this.page = event.pageIndex; this.itemsPerPage = event.pageSize; this.length = event.length; this.search(); } iniciarTour(): void { this.joyrideService.startTour({ steps: [ 'titleStep', 'addHardwareStep', 'searchStep', 'tableStep', ], showPrevButton: true, themeColor: '#3f51b5' }); } viewHardwareCollection(hardware: any): void { // Si el hardware ya tiene la colección cargada, abrir directamente if (hardware.hardwareCollection) { this.openHardwareCollectionModal(hardware); } else { // Si no, obtener los detalles completos del hardware profile this.hardwareProfileService.getHardwareProfile(hardware['@id']).subscribe({ next: (hardwareProfile) => { this.openHardwareCollectionModal(hardwareProfile); }, error: (error) => { console.error('Error fetching hardware profile details:', error); this.toastService.error('Error al obtener los detalles del perfil de hardware'); } }); } } private openHardwareCollectionModal(hardwareProfile: any): void { this.dialog.open(HardwareCollectionModalComponent, { width: '800px', maxWidth: '90vw', data: { profile: hardwareProfile, profileName: hardwareProfile.description || `Perfil ID: ${hardwareProfile.id}` } }); } }