import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core'; import {ModalStatus} from "@app/_helpers/modal.states"; import {FormGroup} from "@angular/forms"; import {postForm} from "@app/_forms/apiForms"; import { PartnerJsonld, PartnerService, PostJsonld, PostService, ProductJsonld, ProductService } from "@app/core/api/v1"; import {FormGroupInitializer} from "@app/_helpers/formgroup.initializer"; import {AppHelperService} from "@app/_helpers/app-helper.service"; import {SearchSelectComponent} from "@app/_components/search-select/search-select.component"; import {ListGetDataFunctionType} from "@app/_components/list/list-get-data-function-type"; @Component({ selector: 'app-new-post', templateUrl: './new-post.component.html', styleUrl: './new-post.component.scss' }) export class NewPostComponent implements OnInit { @Input() public posting!: PostJsonld; @Input() public product!: ProductJsonld; @Input() public partner!: PartnerJsonld; @Output() public submit: EventEmitter = new EventEmitter(); @ViewChild('productSearchSelect', { static: false }) productSearchSelect!: SearchSelectComponent; protected readonly SearchSelectComponent = SearchSelectComponent; protected postForm: FormGroup; constructor( private postService: PostService, protected productService: ProductService, protected partnerService: PartnerService, protected appHelperService: AppHelperService, ) { this.postForm = postForm; } ngOnInit(): void { this.postForm = FormGroupInitializer.initFormGroup(this.postForm, this.posting); this.partnerService.partnersIdGet(this.appHelperService.extractId(this.posting.partnerIri)).subscribe( data => { this.partner = data; } ); } getProducts: ListGetDataFunctionType = (index: number, pageSize: number, term?: string) => { return this.productService.productsGetCollection( index, pageSize, term ); } onSubmit() { if (this.postForm.valid) { if (this.posting.id === null || this.posting.id === undefined) { // Create new post this.postService.postsPost( this.postForm.value as PostJsonld ).subscribe( data => { this.postForm.reset(); this.submit.emit(ModalStatus.Submitted); } ); } else { // Edit post this.postService.postsIdPatch( this.appHelperService.extractId(this.posting.id), this.postForm.value as PostJsonld ).subscribe( data => { this.postForm.reset(); this.submit.emit(ModalStatus.Submitted); } ); } } } }