aboutsummaryrefslogtreecommitdiff
path: root/ufund-ui/src/app/components/cupboard/cupboard.component.ts
blob: 42d920cc4502e5295b18615bd65ba7ebac9650a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {CupboardService} from '../../services/cupboard.service';
import {Need} from '../../models/Need';
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';
import {UsersService} from '../../services/users.service';
import {SortingAlgoArrays} from './sorting';
import {Router} from '@angular/router';
import {ModalService} from '../../services/modal.service';

@Component({
    selector: 'app-cupboard',
    standalone: false,
    templateUrl: './cupboard.component.html',
    styleUrl: './cupboard.component.css'
})
export class CupboardComponent implements OnInit {


    @ViewChild("needList") needList?: NeedListComponent
    @ViewChild("searchForm") searchForm!: ElementRef<HTMLInputElement>

    private searchDelay: any;
    needs: Need[] = [];
    searchResults: Need[] = [];
    sortMode = localStorage.getItem('sortMode') as 'Ascending' | 'Descending' ?? 'Ascending';
    itemsPerPage = parseInt(localStorage.getItem('itemsPerPage') ?? '5') ?? 5;
    currentSortAlgo = localStorage.getItem('sortAlgo') ?? 'sortByPriority';

    constructor(
        private cupboardService: CupboardService,
        private authService: AuthService,
        private toastService: ToastsService,
        protected usersService: UsersService,
        private router: Router,
        protected modalService: ModalService
    ) {}

    ngOnInit(): void {
        this.refresh()
    }

    refresh() {
        this.cupboardService.getNeeds().subscribe(n => {
            this.needs = n;
            this.searchResults = this.sortNeeds(this.needs);
        });
        this.searchForm.nativeElement.form?.reset()
    }

    async search(search: any) {
        //wait .25 seconds before searching but cancel if another search is made during the wait to prevent too many api calls

        //remove previous search if it exists
        if (this.searchDelay) {
            clearTimeout(this.searchDelay);
        }
        if (search) {
            this.searchDelay = setTimeout(() => {
                if (search) {
                    console.log("IF BLOCK")
                    this.cupboardService.searchNeeds(search).subscribe((n) => {
                        this.searchResults = this.sortNeeds(n);
                    });
                }
            }, 250);
        } else {
            //user has cleared the search bar, we can skip the timeout for a 1/4 second faster response
            //clear timeout to stop pending search
            clearTimeout(this.searchDelay);
            this.searchResults = this.sortNeeds(this.needs);
        }
    }

    sortNeeds(needs: Need[]) {
        this.saveSortOptions()
        needs = [...needs] // deep copy
        if (this.sortMode == 'Ascending') {
            return needs.sort(SortingAlgoArrays[this.currentSortAlgo].func);
        } else {
            return needs.sort(SortingAlgoArrays[this.currentSortAlgo].func).reverse();
        }
    }

    saveSortOptions() {
        localStorage.setItem('sortMode', this.sortMode);
        localStorage.setItem('sortAlgo', this.currentSortAlgo);
    }

    toggleSortMode(form : any) {
        if (this.sortMode == 'Ascending'){
            this.sortMode = 'Descending'
        } else {
            this.sortMode = 'Ascending'
        }
        this.search(form)
    }

    deleteNeed(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.refresh();
            })
    }

    addToBasket(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, _) =>  {
                        console.error(err);
                        return of();
                    }))
                    .subscribe(() => {
                        let action = {label: "View Basket", onAction: () => this.router.navigate(['/basket'])}
                        this.toastService.sendToast(ToastType.INFO, `"${need.name}" Added to basket`, action)
                        this.usersService.refreshBasket();
                    });
            } else {
                this.toastService.sendToast(ToastType.ERROR, "This need is already in your basket!")
            }
        }
    }

    editItemsPerPage() {
        if (this.itemsPerPage > this.searchResults.length) {
            this.itemsPerPage = this.searchResults.length
        }
        if (this.itemsPerPage < 1) {
            this.itemsPerPage = 1
        }
        localStorage.setItem('itemsPerPage', this.itemsPerPage.toString())
        this.refresh();
    }

    protected readonly SortingAlgorithms = SortingAlgoArrays;
    protected readonly Object = Object;
}