import {Component, OnInit, ViewChild} from '@angular/core'; import { CupboardService } from '../../services/cupboard.service'; import { Need, GoalType } from '../../models/Need'; import { userType } from '../../models/User'; import { catchError, of } from 'rxjs'; import { NeedListComponent } from '../need-list/need-list.component'; import {AuthService} from '../../services/auth.service'; import {ToastsService, ToastType} from '../../services/toasts.service'; @Component({ selector: 'app-cupboard', standalone: false, templateUrl: './cupboard.component.html', styleUrl: './cupboard.component.css' }) export class CupboardComponent implements OnInit { selectedForm?: string = undefined; needs: any; @ViewChild("needList") needList?: NeedListComponent constructor( private cupboardService: CupboardService, private authService: AuthService, private toastService: ToastsService ) {} ngOnInit(): void { this.cupboardService.getNeeds().subscribe(n => this.needs = n); if (this.isManager()) { console.log("Admin view of Cupboard"); } else { console.log("Limited helper view of Cupboard"); } } selectedNeed: any = { name: '', location:'', id: null, maxGoal: null, type: '', urgent: false }; selectedNeedId: number | null = null; searchResults: any[] = []; selectForm(name: string) { //get search results from the need list if (this.needList) { this.searchResults = this.needList.searchResults; } console.log(this.searchResults) this.selectedForm = name; if (name == 'update') { if (this.searchResults) { this.searchResults.forEach((element: any) => { console.log(element) }); } } } async updateSearchResults() { if (this.needList) { while (this.selectedForm == 'update') { this.searchResults = this.needList.searchResults await new Promise(resolve => setTimeout(resolve, 100)); } } } populateForm(need: any): void { this.selectForm('update'); this.selectedNeed = { ...need }; } isManager() { const type = this.authService.getCurrentUser()?.type; return type === ("MANAGER" as unknown as userType); } submit(form: any) { const need: Need = { name: form.name, image: form.image, location: form.location, id: 0, maxGoal: form.maxGoal, type: form.type, urgent: form.urgent ? true : false, filterAttributes: [], current: 0, description: form.description }; console.log("need:", need); console.log("form submitted. creating need: ", need); this.cupboardService.createNeed(need) .pipe(catchError((ex, _) => { if (ex.status == 500) { this.toastService.sendToast(ToastType.ERROR, "Fields cannot be blank"); } else if (ex.status == 400) { this.toastService.sendToast(ToastType.ERROR, ex.error); } else { this.toastService.sendToast(ToastType.ERROR, "Error on creating need"); } return of() })) .subscribe( (result) => { if (result) { console.log("need created successfully"); this.needList?.refresh() } else { console.log("need creation failed"); } } ); } destroy() { } }