· 6 years ago · Nov 30, 2019, 10:20 PM
1//TO DO > CHECK WHY I HAVE AN ERROR IN THE DELETE BUTTON WHEN I PLAY WITH IT.
2
3class Tool {
4 constructor(name, toolName, number, date, returnDate,typeOfId) {
5 this.name = name;
6 this.toolName = toolName;
7 this.number = number;
8 this.date = date;
9 this.returnDate = returnDate;
10 this.typeOfId = typeOfId;
11 }
12
13}
14
15
16
17class UI {
18 static displayTools() {
19 //getting a ref to the array of the active-tools table and the log table from the localStorage.
20 const tools = Store.getTools();
21 const historyTools = Store.getHistoryTools();
22
23 const modalTools = Store.getAllToolsFromModal();
24 console.log("the current modalTools:",modalTools);
25
26 //looping through each tool in the tools array in order to display them in the dom after they get saved.
27 tools.forEach((tool) => UI.addToolToList(tool));
28
29 historyTools.forEach((historytool) => UI.addToolToHistoryList(historytool));
30
31 modalTools.forEach(modalTool => {
32 console.log("tool check",modalTool[Object.keys(modalTool)[2]]);
33 UI.toWhichBoxToAdd(modalTool[Object.keys(modalTool)[0]],modalTool[Object.keys(modalTool)[1]],"view",modalTool[Object.keys(modalTool)[2]],modalTool[Object.keys(modalTool)[3]]);
34
35 });
36 }
37
38 static addToolToList(tool) {
39 //getting a ref to the tbody which we will add tool to it.
40 const list = document.querySelector("#tool-list");
41 //creating a row to add to the list
42 const row = document.createElement("tr");
43 //we insert to the the row, the params we get from the inputs
44 row.innerHTML = `
45 <td class="c1">${tool.name}</td>
46 <td class="c1">${tool.toolName}</td>
47 <td class="c1">${tool.number}</td>
48 <td><button type="button" class="btn btn-danger delete">החזר כלי</button></td>
49 <td><button type="button" class="btn btn-warning edit" id="editButtonActiveList">עריכת כלי</button></td>
50 <td>${tool.date}</td>
51 <td>${tool.typeOfId ? tool.typeOfId : "לא השאיר תעודה"}</td>
52 `;
53
54 //appending the row to the table body
55 list.appendChild(row);
56 }
57
58
59
60
61 static addToolToHistoryList(historyTool) {
62
63 //i get a ref to the history-list which will store the history
64 const historyList = document.querySelector("#history-list");
65 //then i create a tr(row) which will get inserted the specified cells from the "delete event" fucntion that we passing to this function
66 let historyRowTest = document.createElement("tr");
67
68 //then i insert to the row the values that we got from the "delete event" function
69 historyRowTest.innerHTML = `
70 <td>${historyTool.name}</td>
71 <td>${historyTool.toolName}</td>
72 <td>${historyTool.number}</td>
73 <td>${historyTool.date}</td>
74 <td>${historyTool.returnDate}</td>
75 <td>${historyTool.typeOfId}</td>
76
77
78 `;
79
80 //and finally i append the row to the history table
81 historyList.appendChild(historyRowTest);
82
83 }
84
85
86 //clearing each input
87 static clearInputFields() {
88 document.querySelector("#name").value = "";
89 document.querySelector("#toolName").value = "";
90 document.querySelector("#number").value = "";
91
92
93 }
94
95 //REFACTOR The checkIfExists Method
96 static checkIfExists(toolNumber) {
97 //i set a bool variable and set it to false in order to indicate the state of the if statement later.
98 let isTrue = false;
99 ///i select all the tr nodes in the table.
100 const activeList = document.querySelectorAll("#tool-list tr");
101 activeList.forEach(row => {
102 const td = row.querySelectorAll("td")[2];
103 console.log(td.innerHTML);
104 if(td.innerHTML == toolNumber) {
105 isTrue = true;
106 const name = row.querySelectorAll("td")[0].innerHTML;
107 UI.showAlert(`הכלי נמצא בשימוש על ידי ${name}, לכן השאלתו אינה מתאפשרת, אנא בחר כלי אחר`,"red-alert",4500);
108 }
109 });
110 return isTrue;
111 }
112
113 //upgraded version of this func^^
114 static checkIfToolExists(toolNumber) {
115 const allToolsFromActiveList= Store.getTools();
116 const allToolsFromModal = Store.getAllToolsFromModal();
117 let isTrue = false;
118 allToolsFromActiveList.forEach(tool => {
119 if(tool.number === toolNumber) {
120 isTrue = true;
121 let nameWhoTake = tool.name;
122 UI.showAlert(`הכלי נמצא בשימוש על ידי ${nameWhoTake}, לכן השאלתו אינה מתאפשרת, אנא בחר כלי אחר`,"red-alert",4500);
123 }
124 });
125 return isTrue;
126 }
127
128 //strict mode
129 static isValidToolVersion2(toolName) {
130 const allTools = Store.getAllToolsFromModal();
131 let isTrue = true;
132 allTools.forEach(tool => {
133 if(tool.name !== toolName) {
134 isTrue = false;
135 }
136 })
137 return isTrue;
138 }
139
140//
141// static isValidTool(toolName, toolNumber) {
142// const pTools = [];
143// let isTrue = false;
144// const mainDiv = document.querySelector(".maindiv");
145// const allPTags = mainDiv.querySelectorAll("p");
146// allPTags.forEach(pTag => {
147// if (pTag.innerHTML.includes(toolName) || pTag.innerHTML.includes(toolNumber)) {
148// isTrue = true;
149// }
150// });
151//
152// return isTrue;
153// }
154
155 static isExistsInModal() {
156 const arrOfExistingToolsInModal = Store.getAllToolsFromModal();
157 let isTrue = false;
158 const arrOfJustNumbers = []
159 arrOfExistingToolsInModal.forEach(tool => {
160 let getToolNumber = tool.modalToolNum;
161 arrOfJustNumbers.push(getToolNumber);
162 });
163 return arrOfJustNumbers;
164 }
165
166 static deleteLog() {
167 const historyList = document.querySelector("#history-list");
168 console.log(historyList);
169 let secretPass;
170 do {
171 secretPass = prompt("על מנת למחוק את הלוגים אנא הקש את הססמא המתאימה").toLowerCase();
172 } while (secretPass !== "zaq12wsx");
173 alert("קיבלת הרשאות למחוק את הלוגים");
174 //if the user press "OK", We delete the history log.
175 if (confirm("הזדמנות אחרונה, האם אתה בטוח שברצונך למחוק את הלוגים?")) {
176 //if the user decide to click "OK" all the data in the "historyTools" key in localStorage getb deleted.
177 Store.deleteHistoryLog();
178 historyList.innerHTML = "";
179 UI.showAlert("היסטוריית הלוגים נמחקה בהצלחה", "green-alert", 4500);
180 } else {
181 UI.showAlert("לחצת ביטול, היסטוריית הלוגים לא נמחקה", "green-alert", 3000);
182
183 }
184 }
185
186 static showAlert(message,className,delayTime) {
187 const div = document.createElement("div");
188 div.className = `${className}`;
189 const span = document.createElement("span");
190 span.innerHTML = `${message}`;
191 div.appendChild(span);
192 //get a ref to the parent of the form
193 const container = document.querySelector(".container");
194 //getting ref to the form
195 const form = document.querySelector("#tool-form");
196 //then we insert the div we created before the form
197 container.insertBefore(div, form);
198 //removing the alert messege after a delay of 3 seconds with the setTimeOut callback.
199 setTimeout(() => {
200 container.removeChild(div)
201 }, delayTime);
202
203 }
204
205// static addToList(toolName,toolBox) {
206// let p = document.createElement("p");
207// p.innerHTML = toolName;
208// toolBox.appendChild(p);
209// }
210
211
212 static toWhichBoxToAdd(toolName,toolBox,mode = null,id,toolNumber) {
213 //we set a unique id to each element that's how we gonna identify each element.
214
215 const box1 = document.querySelector(".box-1");
216 const box2 = document.querySelector(".box-2");
217 const box3 = document.querySelector(".box-3");
218 const box4 = document.querySelector(".box-4");
219 const box5 = document.querySelector(".box-5");
220 const box6 = document.querySelector(".box-6");
221 const box7 = document.querySelector(".box-7");
222 let p;
223 switch(toolBox) {
224 case 1:
225 p = document.createElement("p");
226 p.innerHTML = `${toolName} ${toolNumber}`;
227 p.id = id;
228 console.log(p.id);
229 box1.appendChild(p);
230 if(mode !== "view") {
231 Store.addToolToModal(toolName,toolBox,p.id,toolNumber);
232 }
233 break;
234 case 2:
235 p = document.createElement("p");
236 p.innerHTML = `${toolName} ${toolNumber}`;
237 p.id = id;
238 console.log(p.id);
239 box2.appendChild(p);
240 if(mode !== "view") {
241 Store.addToolToModal(toolName,toolBox,p.id,toolNumber);
242 }
243 break;
244 case 3:
245 p = document.createElement("p");
246 p.innerHTML = `${toolName} ${toolNumber}`;
247 //setting an unique id for each element.
248 p.id = id;
249 box3.appendChild(p);
250 if(mode !== "view") {
251 Store.addToolToModal(toolName,toolBox,p.id,toolNumber);
252 }
253 break;
254 case 4:
255 p = document.createElement("p");
256 p.innerHTML =`${toolName} ${toolNumber}`;
257 p.id = id;
258 box4.appendChild(p);
259 if(mode !== "view") {
260 Store.addToolToModal(toolName,toolBox,p.id,toolNumber);
261 }
262 break;
263 case 5:
264 p = document.createElement("p");
265 p.innerHTML = `${toolName} ${toolNumber}`;
266 p.id = id;
267 box5.appendChild(p);
268 if(mode !== "view") {
269 Store.addToolToModal(toolName,toolBox,p.id,toolNumber);
270 }
271 break;
272 case 6:
273 p = document.createElement("p");
274 p.innerHTML = `${toolName} ${toolNumber}`;
275 p.id = id;
276 box6.appendChild(p);
277 if(mode !== "view") {
278 Store.addToolToModal(toolName,toolBox,p.id,toolNumber);
279 }
280 break;
281 case 7:
282 p = document.createElement("p");
283 p.innerHTML = `${toolName} ${toolNumber}`;
284 p.id = id;
285 box7.appendChild(p);
286 if(mode !== "view") {
287 Store.addToolToModal(toolName,toolBox,p.id,toolNumber);
288 }
289 break;
290 default:
291 alert(`מגירה ${toolBox} לא קיימת, נסה שוב`);
292 }
293 }
294
295}
296
297
298//***Store class Logic//***********************
299
300class Store {
301
302
303
304 static getAllToolsFromModal() {
305 let modalTools;
306 if(localStorage.getItem("modalTools") === null) {
307 modalTools = [];
308 } else {
309 modalTools = JSON.parse(localStorage.getItem("modalTools"));
310 }
311 return modalTools;
312 }
313
314 static addToolToModal(toolName,toolBox,id,toolNumber) {
315 const currentTools = Store.getAllToolsFromModal();
316 currentTools.push({"name": toolName, "box": toolBox,"unique_id": id ,"modalToolNum": parseInt(toolNumber)});
317 localStorage.setItem("modalTools",JSON.stringify(currentTools));
318 }
319
320
321 static removeToolFromModal(toolID) {
322 //im getting all the current tools in the modalTools key from the localStorage
323 const allToolsFromModal = Store.getAllToolsFromModal();
324 console.log(allToolsFromModal);
325 //then i iterateb over each tool and his index
326 allToolsFromModal.forEach((tool,index)=> {
327 console.log(index);
328 //if the id of the passed in tool is equal to the toolID that passed in it
329 if(tool.unique_id === toolID) {
330 //i remove the tool that pass this test out of the modalTools key array from the localstorage
331 console.log(tool.name, "has been removed!");
332 allToolsFromModal.splice(index,1);
333
334
335
336 }
337
338 });
339 localStorage.setItem("modalTools", JSON.stringify(allToolsFromModal));
340 }
341
342 static editToolFromModal(toolID,updatedToolName,toolBoxNumber,toolNumber) {
343 console.log(updatedToolName);
344 const allToolsFromStorage = Store.getAllToolsFromModal();
345 allToolsFromStorage.forEach((tool,index) => {
346 if(tool.unique_id === toolID) {
347 allToolsFromStorage.splice(index,1,{"name":updatedToolName, "box":toolBoxNumber,"unique_id":tool.unique_id,"modalToolNum":toolNumber});
348 }
349 });
350 localStorage.setItem("modalTools",JSON.stringify(allToolsFromStorage));
351 }
352
353
354 static getTools() {
355 let tools;
356 //checking if there is a tool in the localStorage
357 if (localStorage.getItem("tools") === null) {
358 tools = [];
359 } else {
360 tools = JSON.parse(localStorage.getItem("tools"));
361 }
362
363 return tools;
364
365 }
366
367 static addTool(tool) {
368 console.log("tool number is",tool.number);
369 //first we get the tools from the localStorage by using the getTools function
370 const tools = Store.getTools();
371 tools.push(tool);
372 //t add the tool to the tools array
373// tools.push({"name": tool.name, "toolName":tool.toolName, "toolNumber":tool.number, "date":tool.date,"returnDate":tool.returnDate,"typeOfId":tool.typeOfId});
374// tools.push({"name": nameInput, "toolName":toolName, "date": submitDate, "returnDate": returnDate,"typeOfId": typeOfId});
375 //upadting the tools array in the localStorage with the new elements
376 localStorage.setItem("tools", JSON.stringify(tools));
377 }
378
379 static removeTool(toolNumber) {
380 toolNumber = parseInt(toolNumber);
381 const tools = Store.getTools();
382 //loop through all the tools
383 tools.forEach((tool, index) => {
384 //if the specified tool have the toolNumber that he gets from the event target
385 if (tool.number === toolNumber) {
386 //we remove the tool that pass this check by his index.
387 tools.splice(index, 1);
388 }
389
390 });
391
392 //update the localStorage
393 localStorage.setItem("tools", JSON.stringify(tools));
394 }
395
396
397
398 /*****Logic of localStorage of the history log******/
399 static getHistoryTools() {
400 let historyTools;
401 if (localStorage.getItem("historyTools") === null) {
402 historyTools = [];
403 } else {
404 historyTools = JSON.parse(localStorage.getItem("historyTools"));
405
406 }
407
408 return historyTools;
409 }
410
411
412
413 static addToolToHistoryLog(tool) {
414 const historyTools = Store.getHistoryTools();
415 historyTools.push(tool);
416 localStorage.setItem("historyTools", JSON.stringify(historyTools));
417
418 }
419
420
421 //delete all the data in the "historyTools" in the localStorage if the user decide to click the delete history button and press ok.
422 static deleteHistoryLog() {
423 //i simply remove the key out of the localStorage and the data get deleted.
424 localStorage.removeItem("historyTools");
425 }
426
427}
428
429
430/******EVENTS*********/
431
432//event - display the tools as soon as the DOM is loaded.
433document.addEventListener("DOMContentLoaded", UI.displayTools());
434
435
436
437
438//add a toada option
439const activateTaodaModeButton = document.querySelector("#activateTaodaMode");
440const taodaDiv = document.querySelector(".taodaDiv");
441activateTaodaModeButton.addEventListener("click" , () => {
442 if(taodaDiv.style.display === "none") {
443 taodaDiv.style.display = "block";
444 } else {
445 taodaDiv.style.display = "none";
446 }
447});
448
449
450
451//EVENT- add a TOOL
452const form = document.querySelector("#tool-form");
453//getting ref to the value of each input
454form.addEventListener("submit", (e) => {
455 e.preventDefault();
456 let nameInput = document.querySelector("#name").value.trim();
457 let toolNameInput = document.querySelector("#toolName").value.trim();
458 let numberInput = document.querySelector("#number").value.trim();
459 console.log(numberInput);
460 let typeOfIdInput = document.querySelector("#people-id").value.trim();
461
462 if(typeOfIdInput === "") {
463 console.log("id not used");
464 }
465 numberInput = parseInt(numberInput);
466 console.log("yes:",numberInput);
467 //Validate >> uncomment tom activate strict mode not letting bullshit tools to add.
468// const trueOrNot = UI.isValidToolVersion2(toolNameInput);
469// if (trueOrNot === false) {
470// UI.showAlert(`לא קיים ברשימת הכלים ${toolNameInput}`,"red-alert",4500)
471//// UI.showAlert(`${toolNameInput} מספר ${numberInput} לא קיימת ברשימת הכלים,אנא וודא ששם הכלי או מספר הכלי תקינים`, "red-alert", 4500);
472// return;
473// }
474 if (nameInput === "" || toolNameInput === "" || numberInput === "") {
475 UI.showAlert("אנא מלא את כל השדות על מנת להשתמש במערכת", "red-alert", 3000);
476 return;
477 } else if (isNaN(numberInput)) {
478 UI.showAlert("אנא הכנס מספר כלי אמיתי ותקין", "red-alert", 3000);
479 return;
480 }
481 else {
482 const tool = new Tool(nameInput, toolNameInput, numberInput, new Date().toLocaleString(),null,typeOfIdInput);
483
484 //i store the return value of the function in this variable
485 const isToolInside = UI.checkIfToolExists(numberInput);
486 //if inside is true
487 if (isToolInside === true) {
488 return;
489 }
490
491
492 const isTheToolExistsInModal = UI.isExistsInModal();
493 console.log(isTheToolExistsInModal);
494 //i check if the passed in number is exists in the modal which mean if it exists, i do it by checking if the passed in number is in the arr of the tool numbers from the modal from the local storage
495 if(isTheToolExistsInModal.indexOf(numberInput) == -1) {
496 UI.showAlert(`${numberInput} is not exists, u can't add a tool that isn't exists.`,"red-alert",4500);
497 return;
498 } else {
499
500 //Add tool to UI. we pass into the func the tool var which hold a Tool object and in this func in the row we assign the value of the inputs to each tool property
501 UI.addToolToList(tool);
502
503 //Add the tool to the localStorage
504 Store.addTool(tool);
505
506 //show success message
507 UI.showAlert(` ${toolNameInput} ${numberInput} התווסף בהצלחה לרשימת הכלים, אנא השאר חוגר בשולחן האחמ"ש`, "green-alert", 4500);
508
509 //clear each input field after we submit an entry
510 UI.clearInputFields();
511 }
512 }
513});
514
515
516
517//const editButtonInActiveList = document.querySelector("#editButtonActiveList");
518//editButtonInActiveList.addEventListener("click", (e) => {
519// if(e.target.tagName === "BUTTON") {
520// const theButton = e.target;
521// const theRow = theButton.parentNode.parentNode;
522// const alllTdTags = theRow.querySelectorAll("td");
523// if(theButton.classList.contains("edit")) {
524// alllTdTags.forEach(td => {
525// if(td.classList.contains("c1")) {
526// let input = document.createElement("input");
527// input.type = "text";
528// input.style.width = "100px";
529// input.value = td.innerHTML;
530//
531// theRow.insertBefore(input,td);
532// theButton.textContent = "שמור";
533// theButton.classList.remove("edit");
534// theButton.classList.add("save");
535// }
536// });
537// } else if(theButton.classList.contains("save")) {
538// let allInputsInActiveList = theRow.querySelectorAll("input");
539// allInputsInActiveList.forEach(input => {
540// let updatedTdTag = document.createElement("td");
541// updatedTdTag.innerHTML = input.value;
542// theRow.insertBefore(updatedTdTag,input);
543// theRow.removeChild(input);
544// theButton.classList.remove("save");
545// theButton.classList.add("edit");
546// theButton.textContent = "ערוך כלי";
547//
548//
549// })
550//
551//
552// }
553//
554// }
555//
556//});
557
558//Event - delete a tool
559const list = document.querySelector("#tool-list")
560list.addEventListener("click", (e) => {
561 //if we press on an anchor tagName
562 if (e.target.tagName === "BUTTON") {
563 //we get a ref to the button we pressed on
564 const button = e.target;
565 //we get a ref to the row we pressed on, the anchor is a child of the "td" and "td" is a child of the row
566 const tr = button.parentNode.parentNode;
567// console.log(tr);
568 console.log(button.className);
569
570 if (button.classList.contains("delete")) {
571 if(confirm("האם אתה בטוח שברצונך למחוק את הכלי?")) {
572 // in order to save the row that the user will delete, i "clone" the DOM element with cloneNode() method and store the cloned row into a variable. (the row is the tr variable that we get access to him).
573 //this variable later be passed into the addTooolToHistoryList() function
574 const historyRow = tr.cloneNode(true);
575// console.log(historyRow);
576
577 //now i remove the specified row that i clicked on him from the reguler table body >> The content(name,toolname,tool number) is already saved into another var (historyRow) so i have the content we just deleted saved.
578 list.removeChild(tr);
579
580
581 //we remove the specified tool row that we clicked on the X button by getting the number of the tool
582 Store.removeTool(button.parentElement.previousElementSibling.innerHTML);
583 console.log(typeof(button.parentElement.previousElementSibling.innerHTML));
584
585 //this is the tricky part, I want to get access to the content of the first,second and third cell which contains the name,toolName and tool number
586 // so i selected the historyRow variable which contain all the td cells from the reguler list and extract only the cells that i needed.
587 const firstTd = historyRow.getElementsByTagName("TD")[0].innerHTML;
588 const secondTd = historyRow.getElementsByTagName("TD")[1].innerHTML;
589 const threeTd = historyRow.getElementsByTagName("TD")[2].innerHTML;
590 const takeTimeToolTd = historyRow.getElementsByTagName("TD")[5].innerHTML;
591 const typeOfIdTd = historyRow.getElementsByTagName("TD")[6].innerHTML;
592 console.log(takeTimeToolTd);
593 console.log(typeof(takeTimeToolTd));
594 const historyTool = new Tool(firstTd, secondTd, threeTd, takeTimeToolTd, new Date().toLocaleString(),typeOfIdTd);
595
596 //then we pass the content on the first,second and third cell that contains the name,tool name and tool number to this function. >> this values will be insterted into the history-table later..
597 UI.addToolToHistoryList(historyTool);
598
599 //add the historyTool to the localStorage when i press x.
600 Store.addToolToHistoryLog(historyTool);
601 UI.showAlert(`כלי מספר ${threeTd} הוחזר לרשימת הכלים`, "green-alert", 3000);
602 } else {
603 return;
604 }
605 }
606
607 }
608
609
610});
611
612
613
614
615
616
617
618
619list.addEventListener("click", (e) => {
620 e.preventDefault();
621 if(e.target.tagName == "BUTTON") {
622 const theButton = e.target;
623 const theRow = theButton.parentNode.parentNode;
624 const alllTdTags = theRow.querySelectorAll("td");
625 if(theButton.classList.contains("edit")) {
626 alllTdTags.forEach(td => {
627 if(td.classList.contains("c1")) {
628 let input = document.createElement("input");
629 input.type = "text";
630 input.style.width = "100px";
631 input.value = td.innerHTML;
632
633 theRow.insertBefore(input,td);
634 theButton.textContent = "שמור";
635 theButton.classList.remove("edit");
636 theButton.classList.add("save");
637 }
638 });
639 } else if(theButton.classList.contains("save")) {
640 let allInputsInActiveList = theRow.querySelectorAll("input");
641 allInputsInActiveList.forEach(input => {
642 let updatedTdTag = document.createElement("td");
643 updatedTdTag.innerHTML = input.value;
644 theRow.insertBefore(updatedTdTag,input);
645 theRow.removeChild(input);
646 theButton.classList.remove("save");
647 theButton.classList.add("edit");
648 theButton.textContent = "ערוך כלי";
649
650
651 });
652 }
653 }
654});
655
656
657
658
659
660
661
662
663
664//DELETE The history-table content when we press on the delete history button.
665const histryLogButton = document.querySelector("#deleteHistoryLog");
666const historyList = document.querySelector("#history-list");
667histryLogButton.addEventListener("click", e => {
668 //if there isbt any key by the name histoyTools
669 if(localStorage.getItem("historyTools") === null) {
670 UI.showAlert("אין לוגים למחיקה כרגע","red-alert",3000);
671 return;
672 } else {
673 UI.deleteLog();
674 }
675
676});
677
678
679
680
681//getting a ref to the show current list button.
682const showToolListButton = document.querySelector("#currentToolList");
683//if the button has been clicked
684showToolListButton.addEventListener("click", () => {
685 // we show the bg-modal
686 document.querySelector(".bg-modal").style.display = "flex";
687
688});
689
690//if the user clicked on the x button in the modal
691const closeButton = document.querySelector(".close");
692closeButton.addEventListener("click", () => {
693 //we hide the modal.
694 document.querySelector(".bg-modal").style.display = "none";
695
696});
697
698
699
700//Dom selectors for the add tool mode.
701const activateModeButton = document.querySelector("#activateModeButton");
702const addModeDiv = document.querySelector(".addModeDiv");
703const addModeDivButton = document.querySelector("#addModeDivButton")
704const addModeToolNameInput = document.querySelector("#addModeToolNameInput");
705const addModeToolBoxInput = document.querySelector("#addModeToolBoxInput");
706const addModeToolNumberInput = document.querySelector("#addModeToolNumberInput");
707
708//checking wheter to show activate mode or not.
709activateModeButton.addEventListener("click", () => {
710 if(addModeDiv.style.display == "none") {
711 addModeDiv.style.display = "block";
712 } else {
713 addModeDiv.style.display = "none";
714 }
715});
716
717
718//EVENT HANDLER FOR ADDING MODE.
719addModeDivButton.addEventListener("click" , () => {
720 let toolName = addModeToolNameInput.value.trim();
721 let toolNumber = addModeToolNumberInput.value.trim();
722 let toolBox = parseInt(addModeToolBoxInput.value.trim());
723 if(toolName === "" || toolBox === "" || isNaN(toolBox) || isNaN(toolNumber)) {
724 alert("אנא מלא את כל השדות כראוי על מנת להמשיך");
725 document.querySelector("#addModeToolNameInput").value = "";
726 document.querySelector("#addModeToolBoxInput").value = "";
727 document.querySelector("#addModeToolNumberInput").value = "";
728 return;
729 } else {
730 UI.toWhichBoxToAdd(toolName,toolBox,"add",new Date().valueOf(),toolNumber);
731 document.querySelector("#addModeToolNameInput").value = "";
732 document.querySelector("#addModeToolBoxInput").value = "";
733 document.querySelector("#addModeToolNumberInput").value = "";
734 }
735
736});
737
738
739
740//EVENT HANDLER FOR DELETE MODE
741const deleteModeButton = document.querySelector("#activateDeleteModeButton");
742const mainDiv = document.querySelector(".maindiv");
743deleteModeButton.addEventListener("click" , () => {
744 let allPTagsInsideModal = mainDiv.querySelectorAll("p");
745 document.querySelector("#activateDeleteModeButton").classList.toggle("buttonDeactivated");
746 console.log(deleteModeButton);
747 if(deleteModeButton.classList.contains("buttonDeactivated")){
748 deleteModeButton.textContent = "סגירת מצב מחיקה";
749 allPTagsInsideModal.forEach(p => {
750 p.addEventListener("click" , (e) => {
751 console.log("mode button:",deleteModeButton);
752 if(deleteModeButton.className === "btn btn-danger") {
753 deleteModeButton.textContent = "הפעלת מצב מחיקה";
754 return;
755 } else {
756 if(e.target.tagName === "P") {
757 console.log("mode button:",deleteModeButton)
758 let boxNumber = e.target.parentNode;
759 console.log("boxNumber:",boxNumber);
760 console.log(boxNumber);
761 let toolToRemove = e.target;
762 console.log(toolToRemove.id);
763 Store.removeToolFromModal(toolToRemove.id)
764 boxNumber.removeChild(toolToRemove);
765 }
766 }
767
768 });
769 })
770 }
771
772});
773
774
775
776const editModeButton = document.querySelector("#activateEditModeButton");
777editModeButton.addEventListener("click", (e) => {
778 let allPTagsInsideModal = mainDiv.querySelectorAll("p");
779 if(e.target.tagName === "BUTTON") {
780 let button = e.target;
781 if(button.classList.contains("edit")) {
782 allPTagsInsideModal.forEach(p => {
783 p.addEventListener("click" , e => {
784 let currentBoxNumber = e.target.parentNode;
785 //getting ref to which p tag i clicked on
786 let toolToEdit = e.target;
787 console.log("toolToEdit id:",toolToEdit.id);
788 let input = document.createElement("input");
789 input.type = "text";
790 input.value = toolToEdit.textContent;
791
792 //setting the id of the input we created to the id of the p tag i clicked on
793 input.id = toolToEdit.id;
794 console.log("same id:",input.id)
795
796
797 //inserting the input tag in place of the p tag i clicked on.
798 currentBoxNumber.insertBefore(input,toolToEdit);
799 currentBoxNumber.removeChild(toolToEdit);
800 button.textContent = "שמור שינויים";
801 button.classList.remove("edit");
802 button.classList.add("save");
803 });
804 });
805 } else if(button.classList.contains("save")) {
806 //getting ref to all the inputs that exists in the modal after we pressed on edit.
807 let allInputsInModal = mainDiv.querySelectorAll("input");
808 //loop through each existing input
809 allInputsInModal.forEach(input => {
810 //getting ref to the parent div of the input which is the the box
811 let currentBoxNumber = input.parentNode;
812 console.log(currentBoxNumber);
813 let newInputTool = input;
814
815
816 let updatedToolPTag = document.createElement("p");
817 //setting the id of the new p element to be equal to the id of the input.
818 updatedToolPTag.id = newInputTool.id;
819 //i set the number of the updatedTool to be equal to the input in order to save the updatedTool with the same number field in storage.
820 updatedToolPTag.number = newInputTool.number;
821 updatedToolPTag.innerHTML = newInputTool.value;
822 console.log("my id is:",updatedToolPTag.id);
823 console.log(updatedToolPTag.innerHTML);
824 let currentName = updatedToolPTag.innerHTML;
825 let currentBox = currentBoxNumber.className;
826 //getting just the number of the box in order to pass it to be saved in the storage.
827 let getJustTheBoxNum = parseInt(currentBox.slice(4));
828 console.log(typeof getJustTheBoxNum);
829 console.log(currentBox);
830 console.log(getJustTheBoxNum);
831
832
833 Store.editToolFromModal(updatedToolPTag.id,currentName,getJustTheBoxNum,updatedToolPTag.number);
834 //inserting the updated p tag in place of the input after i click on the save.
835// Store.editToolFromModal(newInputTool.id,updatedToolPTag.name)
836 currentBoxNumber.insertBefore(updatedToolPTag,newInputTool);
837 currentBoxNumber.removeChild(newInputTool);
838 button.textContent = "הפעל מצב עריכה";
839 button.classList.remove("save");
840 button.classList.add("edit");
841
842 });
843
844 }
845 }
846});