import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core'; import {FormGroup} from "@angular/forms"; import {contactForm} from "@app/_forms/apiForms"; import {ContactJsonld, ContactService, MediaService, PartnerJsonld} from "@app/core/api/v1"; import {Subscription} from "rxjs"; import {ModalContent} from "@app/_interfaces/modalContent"; import {ModalStatus} from "@app/_helpers/modal.states"; import {FormGroupInitializer} from "@app/_helpers/formgroup.initializer"; import {TranslateService} from "@ngx-translate/core"; import {ApiConverter} from "@app/_helpers/api.converter"; @Component({ selector: 'app-new-contact', templateUrl: './new-contact.component.html', styleUrl: './new-contact.component.scss' }) export class NewContactComponent implements ModalContent, OnInit { @Input() public contact!: ContactJsonld; @Output() public submit: EventEmitter = new EventEmitter(); protected contactForm: FormGroup; protected selectedImage: File | null; protected contactSub: Subscription; protected mediaSub: Subscription; constructor( private contactService: ContactService, private mediaService: MediaService, private translateService: TranslateService ) { this.contactForm = contactForm; this.selectedImage = null; this.contactSub = new Subscription(); this.mediaSub = new Subscription(); } ngOnInit(): void { this.contactForm = FormGroupInitializer.initFormGroup(this.contactForm, this.contact); console.log(this.contactForm); } // On submit form: Check if image is set onSubmit() { if (this.selectedImage !== null) { this.mediaSub = this.mediaService.mediasPost( this.selectedImage ).subscribe( data => { this.contactForm.patchValue({"image": data.id}); this.submitForm(); } ); } else { this.submitForm(); } } // Submit all values of the form to the backend submitForm() { if (this.contactForm.valid) { if (this.contact.id === null || this.contact.id === undefined) { // Create new contact this.contactSub = this.contactService.contactsPost( this.contactForm.value as ContactJsonld ).subscribe( data => { this.contactForm.reset(); this.submit.emit(ModalStatus.Submitted); } ); } else { // Edit contact this.contactSub = this.contactService.contactsIdPatch( ApiConverter.extractId(this.contact.id), this.contactForm.value as ContactJsonld ).subscribe( data => { this.contactForm.reset(); this.submit.emit(ModalStatus.Submitted); } ); } } } // If file is selected, convert it onFileSelected(event: any) { const file: File = event.target.files[0]; if (file) { this.selectedImage = file; } } onDeleteImage() { let confirmMessage = ""; this.translateService.get('system.delete-image').subscribe((translation: string) => { confirmMessage = translation; }); const userConfirmed = window.confirm(confirmMessage); if (userConfirmed) { this.contactForm.patchValue({"image": null}); this.contactForm.patchValue({"imageUrl": null}); } } }