Browse Source

Moved util functions in own file

Arnaud Vergnet 4 years 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
 import type {CustomTheme} from "../../managers/ThemeManager";
17
 import type {CustomTheme} from "../../managers/ThemeManager";
18
 import {Collapsible} from "react-navigation-collapsible";
18
 import {Collapsible} from "react-navigation-collapsible";
19
 import {StackNavigationProp} from "@react-navigation/stack";
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
 const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/washinsa/washinsa.json";
22
 const DATA_URL = "https://etud.insa-toulouse.fr/~amicale_app/washinsa/washinsa.json";
24
 
23
 
27
 const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
26
 const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
28
 const LIST_ITEM_HEIGHT = 64;
27
 const LIST_ITEM_HEIGHT = 64;
29
 
28
 
30
-type machine = {
29
+export type Machine = {
31
     number: string,
30
     number: string,
32
     state: string,
31
     state: string,
33
     startTime: string,
32
     startTime: string,
45
 type State = {
44
 type State = {
46
     refreshing: boolean,
45
     refreshing: boolean,
47
     modalCurrentDisplayItem: React.Node,
46
     modalCurrentDisplayItem: React.Node,
48
-    machinesWatched: Array<machine>,
47
+    machinesWatched: Array<Machine>,
49
     bannerVisible: boolean,
48
     bannerVisible: boolean,
50
 };
49
 };
51
 
50
 
59
     modalRef: Object;
58
     modalRef: Object;
60
 
59
 
61
     fetchedData: Object;
60
     fetchedData: Object;
62
-    allMachines: Array<machine>;
63
 
61
 
64
     state = {
62
     state = {
65
         refreshing: false,
63
         refreshing: false,
78
         modalStateStrings[ProxiwashConstants.machineStates["EN COURS"]] = i18n.t('proxiwashScreen.modal.running');
76
         modalStateStrings[ProxiwashConstants.machineStates["EN COURS"]] = i18n.t('proxiwashScreen.modal.running');
79
         modalStateStrings[ProxiwashConstants.machineStates.HS] = i18n.t('proxiwashScreen.modal.broken');
77
         modalStateStrings[ProxiwashConstants.machineStates.HS] = i18n.t('proxiwashScreen.modal.broken');
80
         modalStateStrings[ProxiwashConstants.machineStates.ERREUR] = i18n.t('proxiwashScreen.modal.error');
78
         modalStateStrings[ProxiwashConstants.machineStates.ERREUR] = i18n.t('proxiwashScreen.modal.error');
81
-        this.allMachines = [];
82
     }
79
     }
83
 
80
 
84
     /**
81
     /**
124
      * @param item The item to extract the key from
121
      * @param item The item to extract the key from
125
      * @return {*} The extracted key
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
      * Setups notifications for the machine with the given ID.
128
      * Setups notifications for the machine with the given ID.
142
      * Another will be send a few minutes before the end, based on the value of reminderNotifTime
130
      * Another will be send a few minutes before the end, based on the value of reminderNotifTime
143
      *
131
      *
144
      * @param machine The machine to watch
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
                 .then(() => {
137
                 .then(() => {
151
                     this.saveNotificationToState(machine);
138
                     this.saveNotificationToState(machine);
152
                 })
139
                 })
176
      *
163
      *
177
      * @param machine
164
      * @param machine
178
      */
165
      */
179
-    saveNotificationToState(machine: machine) {
166
+    saveNotificationToState(machine: Machine) {
180
         let data = this.state.machinesWatched;
167
         let data = this.state.machinesWatched;
181
         data.push(machine);
168
         data.push(machine);
182
         this.saveNewWatchedList(data);
169
         this.saveNewWatchedList(data);
187
      *
174
      *
188
      * @param machine
175
      * @param machine
189
      */
176
      */
190
-    removeNotificationFromState(machine: machine) {
177
+    removeNotificationFromState(machine: Machine) {
191
         let data = this.state.machinesWatched;
178
         let data = this.state.machinesWatched;
192
         for (let i = 0; i < data.length; i++) {
179
         for (let i = 0; i < data.length; i++) {
193
             if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
180
             if (data[i].number === machine.number && data[i].endTime === machine.endTime) {
198
         this.saveNewWatchedList(data);
185
         this.saveNewWatchedList(data);
199
     }
186
     }
200
 
187
 
201
-    saveNewWatchedList(list: Array<machine>) {
188
+    saveNewWatchedList(list: Array<Machine>) {
202
         this.setState({machinesWatched: list});
189
         this.setState({machinesWatched: list});
203
         AsyncStorageManager.getInstance().savePref(
190
         AsyncStorageManager.getInstance().savePref(
204
             AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.key,
191
             AsyncStorageManager.getInstance().preferences.proxiwashWatchedMachines.key,
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
      * Creates the dataset to be used by the flatlist
197
      * Creates the dataset to be used by the flatlist
251
      *
198
      *
252
      * @param fetchedData
199
      * @param fetchedData
260
             AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
207
             AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
261
         }
208
         }
262
         this.fetchedData = data;
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
         return [
212
         return [
266
             {
213
             {
267
                 title: i18n.t('proxiwashScreen.dryers'),
214
                 title: i18n.t('proxiwashScreen.dryers'),
299
      *
246
      *
300
      * @param machine The machine to set notifications for
247
      * @param machine The machine to set notifications for
301
      */
248
      */
302
-    onSetupNotificationsPress(machine: machine) {
249
+    onSetupNotificationsPress(machine: Machine) {
303
         if (this.modalRef) {
250
         if (this.modalRef) {
304
             this.modalRef.close();
251
             this.modalRef.close();
305
         }
252
         }
326
         if (ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates["EN COURS"]) {
273
         if (ProxiwashConstants.machineStates[item.state] === ProxiwashConstants.machineStates["EN COURS"]) {
327
             button =
274
             button =
328
                 {
275
                 {
329
-                    text: this.isMachineWatched(item.number) ?
276
+                    text: isMachineWatched(item, this.state.machinesWatched) ?
330
                         i18n.t("proxiwashScreen.modal.disableNotifications") :
277
                         i18n.t("proxiwashScreen.modal.disableNotifications") :
331
                         i18n.t("proxiwashScreen.modal.enableNotifications"),
278
                         i18n.t("proxiwashScreen.modal.enableNotifications"),
332
                     icon: '',
279
                     icon: '',
435
         return (
382
         return (
436
             <ProxiwashListItem
383
             <ProxiwashListItem
437
                 item={item}
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
                 isDryer={isDryer}
387
                 isDryer={isDryer}
441
                 height={LIST_ITEM_HEIGHT}
388
                 height={LIST_ITEM_HEIGHT}
442
             />
389
             />

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

1
 // @flow
1
 // @flow
2
 
2
 
3
 import {checkNotifications, requestNotifications, RESULTS} from 'react-native-permissions';
3
 import {checkNotifications, requestNotifications, RESULTS} from 'react-native-permissions';
4
+import AsyncStorageManager from "../managers/AsyncStorageManager";
4
 
5
 
5
 const PushNotification = require("react-native-push-notification");
6
 const PushNotification = require("react-native-push-notification");
6
 
7
 
8
+const reminderIdMultiplicator = 100;
9
+
7
 /**
10
 /**
8
  * Async function asking permission to send notifications to the user
11
  * Async function asking permission to send notifications to the user
9
  *
12
  *
29
 }
32
 }
30
 
33
 
31
 function createNotifications(machineID: string, date: Date) {
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
     PushNotification.localNotificationSchedule({
50
     PushNotification.localNotificationSchedule({
33
         title: "Title",
51
         title: "Title",
34
         message: "Message",
52
         message: "Message",
57
                 });
75
                 });
58
         } else {
76
         } else {
59
             PushNotification.cancelLocalNotifications({id: machineID});
77
             PushNotification.cancelLocalNotifications({id: machineID});
78
+            let reminderId = reminderIdMultiplicator * parseInt(machineID);
79
+            PushNotification.cancelLocalNotifications({id: reminderId.toString()});
60
             resolve();
80
             resolve();
61
         }
81
         }
62
     });
82
     });

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

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