-
Notifications
You must be signed in to change notification settings - Fork 1
/
foods.js
370 lines (334 loc) · 10.4 KB
/
foods.js
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
function initializeStorage() {
if (localStorage.getItem('all-foods') == null ) {
saveFoodList('all-foods', []);
};
if (localStorage.getItem('breakfast') == null ) {
saveFoodList('breakfast', []);
};
if (localStorage.getItem('lunch') == null ) {
saveFoodList('lunch', []);
};
if (localStorage.getItem('snack') == null ) {
saveFoodList('snack', []);
};
if (localStorage.getItem('dinner') == null ) {
saveFoodList('dinner', []);
};
}
function reloadTables() {
emptyTables();
var result = true;
result = loadFoodList($('#food-list'));
result = result && loadFoodList($('#foods-for-meals'));
result = result && loadFoodList($('#meal-breakfast'));
result = result && loadFoodList($('#meal-lunch'));
result = result && loadFoodList($('#meal-snack'));
result = result && loadFoodList($('#meal-dinner'));
if (result) {
updateLineListener();
deleteButtonListener();
}
updateTotals();
}
function updateTotals(){
var totalGoal = goalCalories();
var totalConsumed = getTotalCaloriesFromMeals();
var totalRemaining = totalGoal - totalConsumed;
$('#total-summary').children('tfoot').children().children('.total-goal-calories').text(totalGoal);
$('#total-summary').children('tfoot').children().children('.total-calories').text(totalConsumed);
$('#total-summary').children('tfoot').children().children('.remaining-calories').text(totalRemaining);
colorRemainingCalories('#total-summary', totalRemaining);
}
function goalCalories(whichTable){
// 200 for Snacks, 400 for Breakfast, 600 for Lunch and 800 for Dinner
var snackGoal = 200;
var breakfastGoal = 400;
var lunchGoal = 600;
var dinnerGoal = 800;
if (whichTable == null) {
return snackGoal + breakfastGoal + lunchGoal + dinnerGoal;
} else {
if (whichTable.attr('id') == "meal-snack") {
return snackGoal;
}
if (whichTable.attr('id') == "meal-breakfast") {
return breakfastGoal;
}
if (whichTable.attr('id') == "meal-lunch") {
return lunchGoal;
}
if (whichTable.attr('id') == "meal-dinner") {
return dinnerGoal;
}
}
}
function emptyTables() {
$('tbody').empty();
}
function loadFoods(location){
var foodsRaw = localStorage.getItem(location);
return $.parseJSON(foodsRaw);
}
var API = 'https://peaceful-plains-83998.herokuapp.com'
function loadFoodsFromApi(){
var foodsRaw = $.ajax({
url: API + '/api/all-foods',
method: 'GET'
}).done(function(data){
console.log(data)
return data
}).fail(function(error){
console.log(error);
})
}
function loadFoodList(whichTable) {
if (whichTable.attr('id') == "food-list" || whichTable.attr('id') == "foods-for-meals") {
// var foods = loadFoods('all-foods');
var foods = loadFoodsFromApi;
debugger;
// console.log(foods)
} else {
if (whichTable.attr('id') == "meal-breakfast"){
var foods = loadFoods('breakfast');
};
if (whichTable.attr('id') == "meal-lunch"){
var foods = loadFoods('lunch');
};
if (whichTable.attr('id') == "meal-snack"){
var foods = loadFoods('snack');
};
if (whichTable.attr('id') == "meal-dinner"){
var foods = loadFoods('dinner');
};
var total = totalCalories(foods) || 0;
var remaining = remainingCalories(whichTable, total) || 0;
$(whichTable).children('tfoot').children().children('.total-calories').text(total);
$(whichTable).children('tfoot').children().children('.remaining-calories').text(remaining);
colorRemainingCalories(whichTable, remaining);
};
if (foods != null) {
var checkBox = whichTable.attr('id') == "foods-for-meals";
var deleteButton = whichTable.attr('id') != "foods-for-meals";
foods.forEach(function(oneFood){
foodTableSingleRow(whichTable, oneFood.name, oneFood.calories, oneFood.id, deleteButton, checkBox, false);
});
return true;
} else {
return false
}
}
function getTotalCaloriesFromMeals(){
var mealTables = [$('#meal-breakfast'), $('#meal-lunch'), $('#meal-snack'), $('#meal-dinner')];
var totalCalories = 0;
mealTables.forEach(function(mealTable){
totalCalories += parseInt($(mealTable).children('tfoot').children().children('.total-calories').text());
});
return totalCalories;
}
function totalCalories(foods){
var total = 0;
if (foods != null) {
foods.forEach(function(oneFood){
total += parseInt(oneFood.calories) || 0;
});
}
return total;
}
function remainingCalories(whichTable, total){
return goalCalories(whichTable) - total;
}
function colorRemainingCalories(whichTable, remaining){
if (remaining < 0) {
$(whichTable).children('tfoot').children().children('.remaining-calories').css('color', 'red');
} else {
$(whichTable).children('tfoot').children().children('.remaining-calories').css('color', 'green');
}
}
function foodTableSingleRow(whichTable, name, calories, id, deleteButton, checkBox, addToList){
var oneRowHtml = '<tr class="food-row">';
if (deleteButton) {
oneRowHtml += '<td class="hidden food-id"><span>' + id + '</span></td><td class="food-name">' + name + '</td><td class="food-calories">' + calories + '</td><td class="food-delete"><button>✕</button></td>';
}
if (checkBox) {
oneRowHtml = oneRowHtml + '<td class="hidden food-id"><span>'+ id + '</span></td><td><input type="checkbox"></td>' + '<td class="food-name">' + name + '</td><td class="food-calories">' + calories + '</td>';
}
oneRowHtml += '</tr>';
$(whichTable).append(oneRowHtml);
}
function removeFood(location, foodId){
if (location == "food-list"){
location = 'all-foods';
};
var data = loadFoods(location);
data = $.grep(data, function(e){
return e.id != foodId;
});
saveFoodList(location, data);
reloadTables();
}
function deleteButtonListener() {
$(".food-delete button").on('click', function() {
var location = $(this).parentsUntil('table').parent().attr('id');
var foodId = $(this).closest('tr').children('.food-id').text();
var data = location.replace('meal-','');
removeFood(data, foodId)
});
}
function saveFoodList(location, data){
data = sortFoods(data);
localStorage.setItem(location, JSON.stringify(data));
return data;
}
function updateFoodList(location, updatedObject){
var data = loadFoods(location);
var idIncluded = $.grep(data, function(e){
return e.id == updatedObject.id;
});
if (idIncluded.length > 0){
data = $.grep(data, function(e){
return e.id != updatedObject.id;
});
data.push(updatedObject);
saveFoodList(location, data);
reloadTables();
};
}
function updateMealLists(updatedObject){
updateFoodList('breakfast', updatedObject);
updateFoodList('lunch', updatedObject);
updateFoodList('snack', updatedObject);
updateFoodList('dinner', updatedObject);
}
function addToFoodList(row){
var objectId = $(row).children('.food-id').text();
var newName = $(row).children('.food-name').text();
var newCalories = $(row).children('.food-calories').text();
updatedObject = {name: newName, calories: newCalories, id: objectId };
updateFoodList('all-foods', updatedObject);
updateMealLists(updatedObject);
return updatedObject;
}
function updateLineListener() {
$('#food-list .food-name,.food-calories').on('click', function(event) {
var $input = $('<input>', {
value: $(event.target).text(),
type: 'text',
blur: function() {
$(event.target).text(this.value);
addToFoodList($(event.target).parent());
},
keyup: function(e) {
if (e.which === 13) {
$input.blur();
};
}
}).appendTo( $(event.target).empty() ).focus();
});
}
function sortFoods(allFoods){
return allFoods.sort(function (a,b) {
return b.id - a.id;
});
}
function addFood() {
clearErrors();
validateInputs();
if ( $('#name-field input').val() != '' && $('#calories-field input').val() != '') {
var name = $('#name-field input').val();
var calories = $('#calories-field input').val();
var allFoods = loadFoods('all-foods');
if (allFoods == null) {
allFoods = [];
}
clearInputs();
var newFood = createNewFood(name, calories);
allFoods.push(newFood);
saveFoodList('all-foods', allFoods);
reloadTables();
};
}
function clearInputs() {
$('#name-field input').val("");
$('#calories-field input').val("");
}
function clearErrors() {
$('#name-field .validation-error').html("");
$('#calories-field .validation-error').html("");
}
function validateInputs() {
if ( $('#name-field input').val() == '') {
$('#name-field .validation-error').html('Please enter a food name');
};
if ( $('#calories-field input').val() == '') {
$('#calories-field .validation-error').html('Please enter a calorie amount');
};
}
function tableFilter() {
var input = $('#food-filter input').val().toUpperCase();
table = document.getElementById('food-list');
rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
td = rows[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(input) > -1 ) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
}
function createNewFood(name, calories){
var obj = {};
obj.name = name;
obj.calories = calories;
obj.id = Date.now();
return obj;
}
function addFoodsToMeal(mealTable){
var checked = $('td input[type="checkbox"]:checked').closest('tr');
if (checked.length > 0) {
var idCollection = [];
$.each(checked, function() {
var id = $(this).children('.hidden').text();
idCollection.push(id);
});
var foods = getFoodsFromIds(idCollection);
var mealFoods = loadFoods(mealTable);
foods.forEach(function(oneFood) {
mealFoods.push(oneFood);
});
saveFoodList(mealTable, mealFoods);
reloadTables();
};
}
function getFoodsFromIds(idCollection){
var allFoods = loadFoods('all-foods');
var selectedFoods = [];
idCollection.forEach(function(i){
allFoods.forEach(function(j){
if (i == j.id){
selectedFoods.push(j);
}
})
})
return selectedFoods;
};
$('document').ready(function() {
// load the data
initializeStorage();
reloadTables();
// event listener for adding food
$('#add-food').on('click', function() {
addFood();
});
// event listener for filtering
$('#food-filter input').keyup(function() {
tableFilter();
});
// event listener for checked boxes
$('.meal-button').on('click', function(){
var mealTable = this.value;
addFoodsToMeal(mealTable);
});
})