]> rtime.felk.cvut.cz Git - coffee/coffee-flask.git/blob - templates/main.js
Remove unused variable
[coffee/coffee-flask.git] / templates / main.js
1 var flask = "{{ url_for('hello', _external=True) }}"
2
3 // State variables
4
5 var updateRemote = undefined;   // defined iff remote server accessible
6 var timeToLogout = undefined;   // defined during logout countdown
7 var logoutTimer;
8 var reloadTimer = undefined;
9 var id_user;                    // ID of the user who is to be accounted for the next coffee
10
11 console.log("hello from flask");
12 //sendJSON("{\"type\":\"empty\"}");
13
14 function update(id, msg) {
15     document.getElementById(id).innerHTML = msg;
16 }
17
18 function replayOfflineQueue() {
19     if (localStorage) {
20         let queue = JSON.parse(localStorage.getItem("offlineQueue")) || [];
21         if (Array.isArray(queue)) {
22             queue.forEach(function (entry) {
23                 updateRemote(entry.data);
24             });
25             localStorage.removeItem("offlineQueue");
26         }
27     }
28 }
29
30 var flavorChosen;
31
32 // Central function to update UI elements. To ensure that the UI is
33 // consistent, other code should only change state variables and then
34 // call this function. This function updates the UI to match the state.
35 function updateUI()
36 {
37     try {
38         let offline = updateRemote === undefined;
39
40         document.getElementById("local").style.display = !offline ? "none" : "block";
41         document.getElementById("remote").style.display = offline ? "none" : "block";
42
43         if (offline) {
44             loadRemote();       // Try to contact the server periodically
45             return;
46         }
47
48         if (id_user !== undefined) {
49             document.getElementById("nextStep").innerHTML = "Now select a beverage on the coffee machineā€¦";
50         } else {
51             document.getElementById("nextStep").innerHTML = "Enjoy your " + flavorChosen + "!";
52         }
53
54         if (timeToLogout !== undefined)
55             document.getElementById("logout_button").innerHTML = '<br>logout<br>(' + timeToLogout + ' s)';
56     }
57     catch (err) {
58         console.log("Error: ", err);
59     }
60 }
61
62 function hiddenUpdateRemote(json) {
63     var msg = JSON.parse(json);
64
65     switch(msg.type) {
66         case "empty":
67             break;
68         case "rfid":
69             login(msg.uid);
70             break;
71         case "keys":
72             var flavor = getFlavor(msg.key);
73             if (flavor !== "") {
74                 addCoffee(flavor);
75             }
76             break;
77         case "ajax_failure":
78             ajax(msg.method, msg.route, msg.data, msg.id);
79             break;
80     }
81     sendLog(json);
82 }
83
84 function loadRemote(string) {
85     var xhr = new XMLHttpRequest();
86     xhr.onreadystatechange = function() {
87         if (this.readyState == 4) {
88             if (this.status == 200) {
89                 update("remote", this.responseText);
90                 updateRemote = hiddenUpdateRemote;
91                 replayOfflineQueue();
92                 updateUI();
93                 clearTimeout(reloadTimer);
94             } else {
95                 reloadTimer = setTimeout(loadRemote, 1000);
96             }
97         }
98     };
99     xhr.open("GET", flask, true);
100     xhr.send();
101 }
102
103 loadRemote();
104
105 function ajax(method, route, data, id) {
106     var xhr = new XMLHttpRequest();
107     xhr.onreadystatechange = function() {
108         if (this.readyState == 4) {
109             if (this.status == 200) {
110                 update(id, this.responseText);
111                 updateUI();
112             } else {
113                 updateRemote = undefined;
114                 updateUI();
115
116                 if (localStorage) {
117                     var ajax_failure = JSON.stringify({
118                         type: "ajax_failure",
119                         method: method,
120                         route: route,
121                         data: data,
122                         id: id
123                     });
124                     let queue = JSON.parse(localStorage.getItem("offlineQueue")) || [];
125                     queue.push({ time: Date.now(), data: ajax_failure });
126                     try {
127                         localStorage.setItem("offlineQueue", JSON.stringify(queue));
128                     }
129                     catch (err) {
130                         console.log(err);
131                     }
132                 }
133             }
134         }
135     };
136     xhr.open(method, flask + route, true);
137     xhr.withCredentials = true;
138     xhr.setRequestHeader("Content-type", "application/json");
139     if (method === "POST") {
140         xhr.send(data);
141     } else {
142         xhr.send();
143     }
144 }
145
146
147 function login(id) {
148     ajax("POST", "login", id, "user");
149     id_user = id;
150     countingTimeLogout(120);
151 }
152
153 function logout() {
154     sendReset();
155     ajax("GET", "logout", "", "user");
156     id_user = undefined;
157     timeToLogout = undefined;
158 }
159
160 function countingTimeLogout(count_time)
161 {
162     clearTimeout(logoutTimer);
163     timeToLogout = count_time;
164     updateUI();
165     if (count_time == 0) {
166         logout();
167     } else {
168         logoutTimer = setTimeout(function() { countingTimeLogout(count_time - 1); }, 1000);
169     }
170 }
171
172 function renameUser() {
173     ajax("GET", "user/rename?name=" +  document.getElementById("username").value, "", "user");
174 }
175
176 function getFlavor(letter) {
177     switch (letter) {
178         case "E": return "espresso";
179         case "C": return "cappuccino";
180         case "B": return "latte macchiato";
181         case "D": return "espresso lungo";
182         default: return "";
183     }
184 }
185
186 function addCoffee(flavor) {
187     var data = JSON.stringify({
188         time: new Date().toISOString(),
189         flavor: flavor,
190         uid: id_user
191     });
192     if (id_user) {
193         ajax("POST", "coffee/add", data, "user");
194         flavorChosen = flavor;
195         id_user = undefined;
196         countingTimeLogout(10); //mean 10 seconds
197     }
198 }
199
200 function sendLog(json) {
201     ajax("POST", "log", json, "log");
202 }