aboutsummaryrefslogtreecommitdiff
path: root/ufund-ui/src/app/components/need-list/need-list.component.ts
blob: 2bbacb0a838ddf7c8509c0c4109fcf5e2f482cd9 (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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import {Component , Output, EventEmitter} from '@angular/core';
import {Need} from '../../models/Need';
import {CupboardService} from '../../services/cupboard.service';
import { UsersService } from '../../services/users.service';
import { userType } from '../../models/User';

interface sortAlgo {
  (a: Need,b: Need): number;
}

// sort functions
const sortByName: sortAlgo = (a: Need, b: Need): number => {
  if(a.name.toLocaleLowerCase() < b.name.toLocaleLowerCase()) {
    return -1;
  }
  return 1;
}

const sortByGoal: sortAlgo = (a: Need, b: Need): number => {
  if(a.maxGoal == b.maxGoal) {
    return sortByName(a,b);
  }
  else if(a.maxGoal > b.maxGoal) {
    return -1;
  }
  return 1;
}

const sortByCompletion: sortAlgo = (a: Need, b: Need): number => {
  if(a.current == b.current) {
    return sortByGoal(a,b);
  }
  else if(a.current > b.current) {
    return -1;
  }
  return 1;
}

const sortByPriority: sortAlgo = (a: Need, b: Need): number => {
  if(a.urgent == b.urgent) {
    return sortByGoal(a,b);
  }
  else if(a.urgent && !b.urgent) {
    return -1;
  }
  return 1;
}

@Component({
  selector: 'app-need-list',
  standalone: false,
  templateUrl: './need-list.component.html',
  styleUrl: './need-list.component.css'
})
export class NeedListComponent {
  selectedNeed: Need | null = null;
  needs: Need[] = [];
  searchResults: Need[] = [];
  sortMode = 'Ascending'

  currentSortAlgo: sortAlgo = sortByPriority;
  sortSelection: string = 'sortByPriority';

  SortingAlgoArrays: {func:sortAlgo,name:string, display:string[]}[] = [
    {func:sortByName,name:"sortByName", display:["Name (A to Z)", "Name (Z to A)"]},
    {func:sortByGoal,name:"sortByGoal", display:["Largest Maximum Goal", "Smallest Maximum Goal"]},
    {func:sortByCompletion,name:"sortByCompletion", display:["Most Completed", "Least Completed"]},
    {func:sortByPriority,name:"sortByPriority", display:["Highest Priority", "Lowest Priority"]},
  ];

  @Output() currentNeed = new EventEmitter<Need>();

  constructor(
    private cupboardService: CupboardService,
    private usersService: UsersService
  ) {}

    refresh() {
        this.cupboardService.getNeeds().subscribe(n => {
          if (this.sortMode == 'Ascending') {
            this.needs = n.sort(this.currentSortAlgo);
          } else {
            this.needs = n.sort(this.currentSortAlgo).reverse();
          }
          this.searchResults = this.needs;
        });
    }

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

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

  private searchDelay: any;

  async search(form: 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 (form) {
      this.searchDelay = setTimeout(() => {

        if (form) {
          //sorting based on algo selected
          this.SortingAlgoArrays.forEach(algo => {
            if(algo.name === this.sortSelection) {
              this.currentSortAlgo = algo.func;
              console.log("changed sorting algorithm to: ", algo.name + this.sortMode)
              return
            }
          });

          const currentSearchValue = form.search; //latest value of the search
          this.cupboardService.searchNeeds(currentSearchValue).subscribe((n) => {
            if (this.sortMode == 'Ascending') {
              this.searchResults = n.sort(this.currentSortAlgo);
            } else {
              this.searchResults = n.sort(this.currentSortAlgo).reverse();
            }

            console.log(currentSearchValue, this.searchResults);
            });
          }
        }, 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.needs;
      }
  }

  delete(id : number) {
    this.cupboardService.deleteNeed(id).subscribe(() => {
      this.needs = this.needs.filter(n => n.id !== id)
    })
  }

  isManager() {
    const type = this.usersService.getCurrentUser()?.type;
    return type === ("MANAGER" as unknown as userType);
  }

  isHelper() {
    const type = this.usersService.getCurrentUser()?.type;
    return type === ("HELPER" as unknown as userType);
  }

  changeText(id : number, text : string) {
    const span = document.getElementById('hover-status-label-' + id);
    if (span) {
      span.innerHTML = ' ' + text;
    }
  }

  add(need: Need) {
    const currentUser = this.usersService.getCurrentUser();
    //console.log("get current user in angular:", currentUser)
    if (currentUser) {
      if (!currentUser.basket.includes(need.id)) {
        currentUser.basket.push(need.id);
        this.usersService.updateUser(currentUser).subscribe(() => {
          this.usersService.refreshBasket();
          error: (err: any) => {
            console.error(err);
          }
        });
      } else {
        window.alert("This need is already in your basket!")
      }


    }

  }

  back() {
    this.searchResults = this.needs;
  }

  select(need : Need) {
    //emit value
    this.currentNeed.emit(need);
    if (this.selectedNeed) {
      //revert already selected need to previous style
      console.log(need.id);
      let button = document.getElementById('need-button-' + this.selectedNeed.id);
      if (button) {
        console.log(button)
        button.style.background = 'lightgray';
        button.style.marginLeft = '0%';
        button.style.width = '98%';
      }
      button = document.getElementById('need-edit-button-' + this.selectedNeed.id);
      if (button) {
        button.style.visibility = 'visible';
      }
    }
      //change selected need to selected style
      this.selectedNeed = need;
      let button = document.getElementById('need-button-' + need.id);
      if (button) {
        button.style.background = 'white';
        button.style.marginLeft = '4%';
        button.style.width = '100%';
      }
      button = document.getElementById('need-edit-button-' + need.id);
      if (button) {
        button.style.visibility = 'hidden';
      }
  }
}