import {Component, Inject} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {HttpClient} from "@angular/common/http"; import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog"; import {ToastrService} from "ngx-toastr"; import {DataService} from "../../images/data.service"; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; @Component({ selector: 'app-create-menu', templateUrl: './create-menu.component.html', styleUrl: './create-menu.component.css' }) export class CreateMenuComponent { baseUrl: string = import.meta.env.NG_APP_BASE_API_URL; menuForm: FormGroup; menuId: string | null = null; softwareProfiles: any[] = []; safeUrl: SafeResourceUrl | null = null; constructor( private fb: FormBuilder, private http: HttpClient, public dialogRef: MatDialogRef, private toastService: ToastrService, private dataService: DataService, private sanitizer: DomSanitizer, @Inject(MAT_DIALOG_DATA) public data: any ) { this.menuForm = this.fb.group({ name: ['', Validators.required], publicUrl: ['', Validators.required], resolution: ['', Validators.required], comments: [''], }); } updateSafeUrl(): void { const url = `${this.baseUrl}/menu/${this.menuForm.get('publicUrl')?.value}`; if (url) { this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url); } else { this.safeUrl = null; } } ngOnInit() { if (this.data) { this.load() } } load(): void { this.dataService.getImage(this.data).subscribe({ next: (response) => { this.menuForm = this.fb.group({ name: [response.name, Validators.required], publicUrl: [response.publicUrl, Validators.required], resolution: [response.resolution, Validators.required], comments: [response.comments], }); this.menuId = response['@id']; this.updateSafeUrl() }, error: (err) => { console.error('Error fetching remote calendar:', err); } }); } save(): void { const payload = { name: this.menuForm.value.name, publicUrl: this.menuForm.value.publicUrl, resolution: this.menuForm.value.resolution, comments: this.menuForm.value.comments, }; if (this.menuId) { this.http.put(`${this.baseUrl}${this.menuId}`, payload).subscribe( (response) => { this.toastService.success('Menu editado correctamente'); this.dialogRef.close(); }, (error) => { this.toastService.error(error['error']['hydra:description']); console.error('Error al editar la imagen', error); } ); } else { this.http.post(`${this.baseUrl}/menus`, payload).subscribe( (response) => { this.toastService.success('Menu añadido correctamente'); this.dialogRef.close(); }, (error) => { this.toastService.error(error['error']['hydra:description']); console.error('Error al añadir el menu', error); } ); } } close(): void { this.dialogRef.close(); } }