import {Component, Input, OnInit} from '@angular/core'; import {GoalType, Need} from '../../models/Need'; import {ActivatedRoute, Router} from "@angular/router"; import {CupboardService} from "../../services/cupboard.service"; import {AuthService} from '../../services/auth.service'; import {catchError, of} from 'rxjs'; import {ToastsService, ToastType} from '../../services/toasts.service'; import {UsersService} from '../../services/users.service'; import {ModalService} from '../../services/modal.service'; @Component({ selector: 'app-need-page', standalone: false, templateUrl: './need-page.component.html', styleUrl: './need-page.component.css' }) export class NeedPageComponent implements OnInit { constructor( private route: ActivatedRoute, private cupboardService: CupboardService, private authService: AuthService, protected usersService: UsersService, private toastService: ToastsService, private router: Router, protected modalService: ModalService ) {} @Input() need!: Need; ngOnInit(): void { const id = Number(this.route.snapshot.paramMap.get('id')); this.cupboardService.getNeed(id).subscribe(n => this.need = n); } add(need: Need) { const currentUser = this.authService.getCurrentUser(); if (currentUser) { if (!currentUser.basket.includes(need.id)) { currentUser.basket.push(need.id); this.usersService.updateUser(currentUser) .pipe(catchError((err, _) => { let action = {label: "View Basket", onAction: () => this.router.navigate(['/basket'])} this.toastService.sendToast(ToastType.INFO, `"${need.name}" Added to basket`, action) return of(); })) .subscribe(() => { this.usersService.refreshBasket(); }); } else { this.toastService.sendToast(ToastType.ERROR, "This need is already in your basket!") } } } delete(id : number) { this.cupboardService.deleteNeed(id) .pipe(catchError((ex, _) => { this.toastService.sendToast(ToastType.ERROR, ex.error) return of() })) .subscribe(() => { this.toastService.sendToast(ToastType.INFO, "Need deleted.") this.router.navigate(['/cupboard']) }) // this.refresh(); } readonly GoalType = GoalType }