Browse Source

Moved util functions in own file

Arnaud Vergnet 1 year ago
parent
commit
e5299ed9c3
3 changed files with 88 additions and 69 deletions
  1. 16
    69
      src/screens/Proxiwash/ProxiwashScreen.js
  2. 20
    0
      src/utils/Notifications.js
  3. 52
    0
      src/utils/Proxiwash.js

+ 16
- 69
src/screens/Proxiwash/ProxiwashScreen.js View File

@@ -17,8 +17,7 @@ import {withCollapsible} from "../../utils/withCollapsible";
17 17
 import type {CustomTheme} from "../../managers/ThemeManager";
18 18
 import {Collapsible} from "react-navigation-collapsible";
19 19
 import {StackNavigationProp} from "@react-navigation/stack";
20
-
21
-const PushNotification = require("react-native-push-notification");
20
+import {getCleanedMachineWatched, getMachineEndDate, isMachineWatched} from "../../utils/Proxiwash";
22 21
 
23 22
 const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/washinsa/washinsa.json";
24 23
 
@@ -27,7 +26,7 @@ let modalStateStrings = {};
27 26
 const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
28 27
 const LIST_ITEM_HEIGHT = 64;
29 28
 
30
-type machine = {
29
+export type Machine = {
31 30
     number: string,
32 31
     state: string,
33 32
     startTime: string,
@@ -45,7 +44,7 @@ type Props = {
45 44
 type State = {
46 45
     refreshing: boolean,
47 46
     modalCurrentDisplayItem: React.Node,
48
-    machinesWatched: Array<machine>,
47
+    machinesWatched: Array<Machine>,
49 48
     bannerVisible: boolean,
50 49
 };
51 50
 
@@ -59,7 +58,6 @@ class ProxiwashScreen extends React.Component<Props, State> {
59 58
     modalRef: Object;
60 59
 
61 60
     fetchedData: Object;
62
-    allMachines: Array<machine>;
63 61
 
64 62
     state = {
65 63
         refreshing: false,
@@ -78,7 +76,6 @@ class ProxiwashScreen extends React.Component<Props, State> {
78 76
         modalStateStrings[ProxiwashConstants.machineStates["EN COURS"]] = i18n.t('proxiwashScreen.modal.running');
79 77
         modalStateStrings[ProxiwashConstants.machineStates.HS] = i18n.t('proxiwashScreen.modal.broken');
80 78
         modalStateStrings[ProxiwashConstants.machineStates.ERREUR] = i18n.t('proxiwashScreen.modal.error');
81
-        this.allMachines = [];
82 79
     }
83 80
 
84 81
     /**
@@ -124,17 +121,8 @@ class ProxiwashScreen extends React.Component<Props, State> {
124 121
      * @param item The item to extract the key from
125 122
      * @return {*} The extracted key
126 123
      */
127
-    getKeyExtractor = (item: machine) => item.number;
128
-
124
+    getKeyExtractor = (item: Machine) => item.number;
129 125
 
130
-    getMachineEndDate(machine: machine) {
131
-        const array = machine.endTime.split(":");
132
-        let date = new Date();
133
-        date.setHours(parseInt(array[0]), parseInt(array[1]));
134
-        if (date < new Date())
135
-            date.setDate(date.getDate() + 1);
136
-        return date;
137
-    }
138 126
 
139 127
     /**
140 128
      * Setups notifications for the machine with the given ID.
@@ -142,11 +130,10 @@ class ProxiwashScreen extends React.Component<Props, State> {
142 130
      * Another will be send a few minutes before the end, based on the value of reminderNotifTime
143 131
      *
144 132
      * @param machine The machine to watch
145
-     * @returns {Promise<void>}
146 133
      */
147
-    setupNotifications(machine: machine) {
148
-        if (!this.isMachineWatched(machine)) {
149
-            Notifications.setupMachineNotification(machine.number, true, this.getMachineEndDate(machine))
134
+    setupNotifications(machine: Machine) {
135
+        if (!isMachineWatched(machine, this.state.machinesWatched)) {
136
+            Notifications.setupMachineNotification(machine.number, true, getMachineEndDate(machine))
150 137
                 .then(() => {
151 138
                     this.saveNotificationToState(machine);
152 139
                 })
@@ -176,7 +163,7 @@ class ProxiwashScreen extends React.Component<Props, State> {
176 163
      *
177 164
      * @param machine
178 165
      */
179
-    saveNotificationToState(machine: machine) {
166
+    saveNotificationToState(machine: Machine) {
180 167
         let data = this.state.machinesWatched;
181 168
         data.push(machine);
182 169
         this.saveNewWatchedList(data);
@@ -187,7 +174,7 @@ class ProxiwashScreen extends React.Component<Props, State> {
187 174
      *
188 175
      * @param machine
189 176
      */
190
-    removeNotificationFromState(machine: machine) {
177
+    removeNotificationFromState(machine: Machine) {
191 178
         let data = this.state.machinesWatched;
192 179
         for (let i = 0; i < data.length; i++) {
193 180
             if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
@@ -198,7 +185,7 @@ class ProxiwashScreen extends React.Component<Props, State> {
198 185
         this.saveNewWatchedList(data);
199 186
     }
200 187
 
201
-    saveNewWatchedList(list: Array<machine>) {
188
+    saveNewWatchedList(list: Array<Machine>) {
202 189
         this.setState({machinesWatched: list});
203 190
         AsyncStorageManager.getInstance().savePref(
204 191
             AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.key,
@@ -207,46 +194,6 @@ class ProxiwashScreen extends React.Component<Props, State> {
207 194
     }
208 195
 
209 196
     /**
210
-     * Checks whether the machine of the given ID has scheduled notifications
211
-     *
212
-     * @param machine
213
-     * @returns {boolean}
214
-     */
215
-    isMachineWatched(machine: machine) {
216
-        let watched = false;
217
-        const list = this.state.machinesWatched;
218
-        for (let i = 0; i < list.length; i++) {
219
-            if (list[i].number === machine.number && list[i].endTime === machine.endTime) {
220
-                watched = true;
221
-                break;
222
-            }
223
-        }
224
-        return watched;
225
-    }
226
-
227
-    getMachineOfId(id: string) {
228
-        for (let i = 0; i < this.allMachines.length; i++) {
229
-            if (this.allMachines[i].number === id)
230
-                return this.allMachines[i];
231
-        }
232
-        return null;
233
-    }
234
-
235
-    getCleanedMachineWatched() {
236
-        const list = this.state.machinesWatched;
237
-        let newList = [];
238
-        for (let i = 0; i < list.length; i++) {
239
-            let machine = this.getMachineOfId(list[i].number);
240
-            if (machine !== null
241
-                && list[i].number === machine.number && list[i].endTime === machine.endTime
242
-                && ProxiwashConstants.machineStates[list[i].state] === ProxiwashConstants.machineStates["EN COURS"]) {
243
-                newList.push(machine);
244
-            }
245
-        }
246
-        return newList;
247
-    }
248
-
249
-    /**
250 197
      * Creates the dataset to be used by the flatlist
251 198
      *
252 199
      * @param fetchedData
@@ -260,8 +207,8 @@ class ProxiwashScreen extends React.Component<Props, State> {
260 207
             AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
261 208
         }
262 209
         this.fetchedData = data;
263
-        this.allMachines = [...data.dryers, ...data.washers];
264
-        this.state.machinesWatched = this.getCleanedMachineWatched();
210
+        this.state.machinesWatched =
211
+            getCleanedMachineWatched(this.state.machinesWatched, [...data.dryers, ...data.washers]);
265 212
         return [
266 213
             {
267 214
                 title: i18n.t('proxiwashScreen.dryers'),
@@ -299,7 +246,7 @@ class ProxiwashScreen extends React.Component<Props, State> {
299 246
      *
300 247
      * @param machine The machine to set notifications for
301 248
      */
302
-    onSetupNotificationsPress(machine: machine) {
249
+    onSetupNotificationsPress(machine: Machine) {
303 250
         if (this.modalRef) {
304 251
             this.modalRef.close();
305 252
         }
@@ -326,7 +273,7 @@ class ProxiwashScreen extends React.Component<Props, State> {
326 273
         if (ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates["EN COURS"]) {
327 274
             button =
328 275
                 {
329
-                    text: this.isMachineWatched(item.number) ?
276
+                    text: isMachineWatched(item, this.state.machinesWatched) ?
330 277
                         i18n.t("proxiwashScreen.modal.disableNotifications") :
331 278
                         i18n.t("proxiwashScreen.modal.enableNotifications"),
332 279
                     icon: '',
@@ -435,8 +382,8 @@ class ProxiwashScreen extends React.Component<Props, State> {
435 382
         return (
436 383
             <ProxiwashListItem
437 384
                 item={item}
438
-                onPress={() => this.onSetupNotificationsPress(item)}
439
-                isWatched={this.isMachineWatched(item)}
385
+                onPress={this.showModal}
386
+                isWatched={isMachineWatched(item, this.state.machinesWatched)}
440 387
                 isDryer={isDryer}
441 388
                 height={LIST_ITEM_HEIGHT}
442 389
             />

+ 20
- 0
src/utils/Notifications.js View File

@@ -1,9 +1,12 @@
1 1
 // @flow
2 2
 
3 3
 import {checkNotifications, requestNotifications, RESULTS} from 'react-native-permissions';
4
+import AsyncStorageManager from "../managers/AsyncStorageManager";
4 5
 
5 6
 const PushNotification = require("react-native-push-notification");
6 7
 
8
+const reminderIdMultiplicator = 100;
9
+
7 10
 /**
8 11
  * Async function asking permission to send notifications to the user
9 12
  *
@@ -29,6 +32,21 @@ export async function askPermissions() {
29 32
 }
30 33
 
31 34
 function createNotifications(machineID: string, date: Date) {
35
+    let reminder = parseInt(AsyncStorageManager.getInstance().preferences.proxiwashNotifications.current);
36
+    if (!isNaN(reminder)) {
37
+        let id = reminderIdMultiplicator * parseInt(machineID);
38
+        let reminderDate = new Date(date);
39
+        reminderDate.setMinutes(reminderDate.getMinutes() - reminder);
40
+        PushNotification.localNotificationSchedule({
41
+            title: "Title",
42
+            message: "Message",
43
+            id: id.toString(),
44
+            date: reminderDate,
45
+        });
46
+        console.log("Setting up notifications for ", date, " and reminder for ", reminderDate);
47
+    } else
48
+        console.log("Setting up notifications for ", date);
49
+
32 50
     PushNotification.localNotificationSchedule({
33 51
         title: "Title",
34 52
         message: "Message",
@@ -57,6 +75,8 @@ export async function setupMachineNotification(machineID: string, isEnabled: boo
57 75
                 });
58 76
         } else {
59 77
             PushNotification.cancelLocalNotifications({id: machineID});
78
+            let reminderId = reminderIdMultiplicator * parseInt(machineID);
79
+            PushNotification.cancelLocalNotifications({id: reminderId.toString()});
60 80
             resolve();
61 81
         }
62 82
     });

+ 52
- 0
src/utils/Proxiwash.js View File

@@ -0,0 +1,52 @@
1
+// @flow
2
+
3
+import type {Machine} from "../screens/Proxiwash/ProxiwashScreen";
4
+import ProxiwashConstants from "../constants/ProxiwashConstants";
5
+
6
+export function getMachineEndDate(machine: Machine) {
7
+    const array = machine.endTime.split(":");
8
+    let date = new Date();
9
+    date.setHours(parseInt(array[0]), parseInt(array[1]));
10
+    if (date < new Date())
11
+        date.setDate(date.getDate() + 1);
12
+    return date;
13
+}
14
+
15
+/**
16
+ * Checks whether the machine of the given ID has scheduled notifications
17
+ *
18
+ * @param machine
19
+ * @param machineList
20
+ * @returns {boolean}
21
+ */
22
+export function isMachineWatched(machine: Machine, machineList: Array<Machine>) {
23
+    let watched = false;
24
+    for (let i = 0; i < machineList.length; i++) {
25
+        if (machineList[i].number === machine.number && machineList[i].endTime === machine.endTime) {
26
+            watched = true;
27
+            break;
28
+        }
29
+    }
30
+    return watched;
31
+}
32
+
33
+function getMachineOfId(id: string, allMachines: Array<Machine>) {
34
+    for (let i = 0; i < allMachines.length; i++) {
35
+        if (allMachines[i].number === id)
36
+            return allMachines[i];
37
+    }
38
+    return null;
39
+}
40
+
41
+export function getCleanedMachineWatched(machineList: Array<Machine>, allMachines: Array<Machine>) {
42
+    let newList = [];
43
+    for (let i = 0; i < machineList.length; i++) {
44
+        let machine = getMachineOfId(machineList[i].number, allMachines);
45
+        if (machine !== null
46
+            && machineList[i].number === machine.number && machineList[i].endTime === machine.endTime
47
+            && ProxiwashConstants.machineStates[machineList[i].state] === ProxiwashConstants.machineStates["EN COURS"]) {
48
+            newList.push(machine);
49
+        }
50
+    }
51
+    return newList;
52
+}

Loading…
Cancel
Save