Application Android et IOS pour l'amicale des élèves https://play.google.com/store/apps/details?id=fr.amicaleinsat.application
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProxiwashScreen.tsx 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. /*
  2. * Copyright (c) 2019 - 2020 Arnaud Vergnet.
  3. *
  4. * This file is part of Campus INSAT.
  5. *
  6. * Campus INSAT is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Campus INSAT is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Campus INSAT. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. import React, { useLayoutEffect, useRef, useState } from 'react';
  20. import {
  21. SectionListData,
  22. SectionListRenderItemInfo,
  23. StyleSheet,
  24. View,
  25. } from 'react-native';
  26. import i18n from 'i18n-js';
  27. import { Avatar, Button, Card, Text, useTheme } from 'react-native-paper';
  28. import { Modalize } from 'react-native-modalize';
  29. import WebSectionList from '../../components/Screens/WebSectionList';
  30. import ProxiwashListItem from '../../components/Lists/Proxiwash/ProxiwashListItem';
  31. import ProxiwashConstants, {
  32. MachineStates,
  33. } from '../../constants/ProxiwashConstants';
  34. import CustomModal from '../../components/Overrides/CustomModal';
  35. import AprilFoolsManager from '../../managers/AprilFoolsManager';
  36. import MaterialHeaderButtons, {
  37. Item,
  38. } from '../../components/Overrides/CustomHeaderButton';
  39. import ProxiwashSectionHeader from '../../components/Lists/Proxiwash/ProxiwashSectionHeader';
  40. import {
  41. getCleanedMachineWatched,
  42. getMachineEndDate,
  43. isMachineWatched,
  44. } from '../../utils/Proxiwash';
  45. import { MASCOT_STYLE } from '../../components/Mascot/Mascot';
  46. import MascotPopup from '../../components/Mascot/MascotPopup';
  47. import type { SectionListDataType } from '../../components/Screens/WebSectionList';
  48. import type { LaundromatType } from './ProxiwashAboutScreen';
  49. import GENERAL_STYLES from '../../constants/Styles';
  50. import { readData } from '../../utils/WebData';
  51. import { useNavigation } from '@react-navigation/core';
  52. import { setupMachineNotification } from '../../utils/Notifications';
  53. import ProximoListHeader from '../../components/Lists/Proximo/ProximoListHeader';
  54. import {
  55. getPreferenceNumber,
  56. getPreferenceObject,
  57. getPreferenceString,
  58. ProxiwashPreferenceKeys,
  59. } from '../../utils/asyncStorage';
  60. import { useProxiwashPreferences } from '../../context/preferencesContext';
  61. import { useSubsequentEffect } from '../../utils/customHooks';
  62. const REFRESH_TIME = 1000 * 10; // Refresh every 10 seconds
  63. const LIST_ITEM_HEIGHT = 64;
  64. export type ProxiwashMachineType = {
  65. number: string;
  66. state: MachineStates;
  67. maxWeight: number;
  68. startTime: string;
  69. endTime: string;
  70. donePercent: string;
  71. remainingTime: string;
  72. program: string;
  73. };
  74. type FetchedDataType = {
  75. dryers: Array<ProxiwashMachineType>;
  76. washers: Array<ProxiwashMachineType>;
  77. };
  78. const styles = StyleSheet.create({
  79. modalContainer: {
  80. flex: 1,
  81. padding: 20,
  82. },
  83. icon: {
  84. backgroundColor: 'transparent',
  85. },
  86. container: {
  87. position: 'absolute',
  88. width: '100%',
  89. height: '100%',
  90. },
  91. });
  92. function ProxiwashScreen() {
  93. const navigation = useNavigation();
  94. const theme = useTheme();
  95. const { preferences, updatePreferences } = useProxiwashPreferences();
  96. const [modalCurrentDisplayItem, setModalCurrentDisplayItem] =
  97. useState<React.ReactElement | null>(null);
  98. const reminder = getPreferenceNumber(
  99. ProxiwashPreferenceKeys.proxiwashNotifications,
  100. preferences
  101. );
  102. const [refresh, setRefresh] = useState(false);
  103. const getMachinesWatched = () => {
  104. const data = getPreferenceObject(
  105. ProxiwashPreferenceKeys.proxiwashWatchedMachines,
  106. preferences
  107. ) as Array<ProxiwashMachineType>;
  108. return data ? (data as Array<ProxiwashMachineType>) : [];
  109. };
  110. const getSelectedWash = () => {
  111. const data = getPreferenceString(
  112. ProxiwashPreferenceKeys.selectedWash,
  113. preferences
  114. );
  115. if (data !== 'washinsa' && data !== 'tripodeB') {
  116. return 'washinsa';
  117. } else {
  118. return data;
  119. }
  120. };
  121. const machinesWatched: Array<ProxiwashMachineType> = getMachinesWatched();
  122. const selectedWash: 'washinsa' | 'tripodeB' = getSelectedWash();
  123. useSubsequentEffect(() => {
  124. // Refresh the list when the selected wash changes
  125. setRefresh(true);
  126. }, [selectedWash]);
  127. const modalStateStrings: { [key in MachineStates]: string } = {
  128. [MachineStates.AVAILABLE]: i18n.t('screens.proxiwash.modal.ready'),
  129. [MachineStates.RUNNING]: i18n.t('screens.proxiwash.modal.running'),
  130. [MachineStates.RUNNING_NOT_STARTED]: i18n.t(
  131. 'screens.proxiwash.modal.runningNotStarted'
  132. ),
  133. [MachineStates.FINISHED]: i18n.t('screens.proxiwash.modal.finished'),
  134. [MachineStates.UNAVAILABLE]: i18n.t('screens.proxiwash.modal.broken'),
  135. [MachineStates.ERROR]: i18n.t('screens.proxiwash.modal.error'),
  136. [MachineStates.UNKNOWN]: i18n.t('screens.proxiwash.modal.unknown'),
  137. };
  138. const modalRef = useRef<Modalize>(null);
  139. useLayoutEffect(() => {
  140. navigation.setOptions({
  141. headerRight: () => (
  142. <MaterialHeaderButtons>
  143. <Item
  144. title={'information'}
  145. iconName={'information'}
  146. onPress={() => navigation.navigate('proxiwash-about')}
  147. />
  148. </MaterialHeaderButtons>
  149. ),
  150. });
  151. }, [navigation]);
  152. /**
  153. * Callback used when the user clicks on enable notifications for a machine
  154. *
  155. * @param machine The machine to set notifications for
  156. */
  157. const onSetupNotificationsPress = (machine: ProxiwashMachineType) => {
  158. if (modalRef.current) {
  159. modalRef.current.close();
  160. }
  161. setupNotifications(machine);
  162. };
  163. /**
  164. * Generates the modal content.
  165. * This shows information for the given machine.
  166. *
  167. * @param title The title to use
  168. * @param item The item to display information for in the modal
  169. * @param isDryer True if the given item is a dryer
  170. * @return {*}
  171. */
  172. const getModalContent = (
  173. title: string,
  174. item: ProxiwashMachineType,
  175. isDryer: boolean
  176. ) => {
  177. let button: { text: string; icon: string; onPress: () => void } | undefined;
  178. let message = modalStateStrings[item.state];
  179. const onPress = () => onSetupNotificationsPress(item);
  180. if (item.state === MachineStates.RUNNING) {
  181. let remainingTime = parseInt(item.remainingTime, 10);
  182. if (remainingTime < 0) {
  183. remainingTime = 0;
  184. }
  185. button = {
  186. text: isMachineWatched(item, machinesWatched)
  187. ? i18n.t('screens.proxiwash.modal.disableNotifications')
  188. : i18n.t('screens.proxiwash.modal.enableNotifications'),
  189. icon: '',
  190. onPress: onPress,
  191. };
  192. message = i18n.t('screens.proxiwash.modal.running', {
  193. start: item.startTime,
  194. end: item.endTime,
  195. remaining: remainingTime,
  196. program: item.program,
  197. });
  198. }
  199. return (
  200. <View style={styles.modalContainer}>
  201. <Card.Title
  202. title={title}
  203. left={() => (
  204. <Avatar.Icon
  205. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  206. color={theme.colors.text}
  207. style={styles.icon}
  208. />
  209. )}
  210. />
  211. <Card.Content>
  212. <Text>{message}</Text>
  213. </Card.Content>
  214. {button ? (
  215. <Card.Actions>
  216. <Button
  217. icon={button.icon}
  218. mode="contained"
  219. onPress={button.onPress}
  220. style={GENERAL_STYLES.centerHorizontal}
  221. >
  222. {button.text}
  223. </Button>
  224. </Card.Actions>
  225. ) : null}
  226. </View>
  227. );
  228. };
  229. /**
  230. * Gets the section render item
  231. *
  232. * @param section The section to render
  233. * @return {*}
  234. */
  235. const getRenderSectionHeader = ({
  236. section,
  237. }: {
  238. section: SectionListData<ProxiwashMachineType>;
  239. }) => {
  240. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  241. const nbAvailable = getMachineAvailableNumber(section.data);
  242. return (
  243. <ProxiwashSectionHeader
  244. title={section.title}
  245. nbAvailable={nbAvailable}
  246. isDryer={isDryer}
  247. />
  248. );
  249. };
  250. /**
  251. * Gets the list item to be rendered
  252. *
  253. * @param item The object containing the item's FetchedData
  254. * @param section The object describing the current SectionList section
  255. * @returns {React.Node}
  256. */
  257. const getRenderItem = (
  258. data: SectionListRenderItemInfo<ProxiwashMachineType>
  259. ) => {
  260. const isDryer = data.section.title === i18n.t('screens.proxiwash.dryers');
  261. return (
  262. <ProxiwashListItem
  263. item={data.item}
  264. onPress={showModal}
  265. isWatched={isMachineWatched(data.item, machinesWatched)}
  266. isDryer={isDryer}
  267. height={LIST_ITEM_HEIGHT}
  268. />
  269. );
  270. };
  271. /**
  272. * Extracts the key for the given item
  273. *
  274. * @param item The item to extract the key from
  275. * @return {*} The extracted key
  276. */
  277. const getKeyExtractor = (item: ProxiwashMachineType): string => item.number;
  278. /**
  279. * Setups notifications for the machine with the given ID.
  280. * One notification will be sent at the end of the program.
  281. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  282. *
  283. * @param machine The machine to watch
  284. */
  285. const setupNotifications = (machine: ProxiwashMachineType) => {
  286. if (!isMachineWatched(machine, machinesWatched)) {
  287. setupMachineNotification(
  288. machine.number,
  289. true,
  290. reminder,
  291. getMachineEndDate(machine)
  292. );
  293. saveNotificationToState(machine);
  294. } else {
  295. setupMachineNotification(machine.number, false);
  296. removeNotificationFromState(machine);
  297. }
  298. };
  299. /**
  300. * Gets the number of machines available
  301. *
  302. * @param isDryer True if we are only checking for dryer, false for washers
  303. * @return {number} The number of machines available
  304. */
  305. const getMachineAvailableNumber = (
  306. data: ReadonlyArray<ProxiwashMachineType>
  307. ): number => {
  308. let count = 0;
  309. data.forEach((machine: ProxiwashMachineType) => {
  310. if (machine.state === MachineStates.AVAILABLE) {
  311. count += 1;
  312. }
  313. });
  314. return count;
  315. };
  316. /**
  317. * Creates the dataset to be used by the FlatList
  318. *
  319. * @param fetchedData
  320. * @return {*}
  321. */
  322. const createDataset = (
  323. fetchedData: FetchedDataType | undefined
  324. ): SectionListDataType<ProxiwashMachineType> => {
  325. if (fetchedData) {
  326. let data = fetchedData;
  327. if (AprilFoolsManager.getInstance().isAprilFoolsEnabled()) {
  328. data = JSON.parse(JSON.stringify(fetchedData)); // Deep copy
  329. AprilFoolsManager.getNewProxiwashDryerOrderedList(data.dryers);
  330. AprilFoolsManager.getNewProxiwashWasherOrderedList(data.washers);
  331. }
  332. fetchedData = data;
  333. const cleanedList = getCleanedMachineWatched(machinesWatched, [
  334. ...data.dryers,
  335. ...data.washers,
  336. ]);
  337. if (cleanedList.length !== machinesWatched.length) {
  338. updatePreferences(
  339. ProxiwashPreferenceKeys.proxiwashWatchedMachines,
  340. cleanedList
  341. );
  342. }
  343. return [
  344. {
  345. title: i18n.t('screens.proxiwash.dryers'),
  346. icon: 'tumble-dryer',
  347. data: data.dryers === undefined ? [] : data.dryers,
  348. keyExtractor: getKeyExtractor,
  349. },
  350. {
  351. title: i18n.t('screens.proxiwash.washers'),
  352. icon: 'washing-machine',
  353. data: data.washers === undefined ? [] : data.washers,
  354. keyExtractor: getKeyExtractor,
  355. },
  356. ];
  357. } else {
  358. return [];
  359. }
  360. };
  361. /**
  362. * Shows a modal for the given item
  363. *
  364. * @param title The title to use
  365. * @param item The item to display information for in the modal
  366. * @param isDryer True if the given item is a dryer
  367. */
  368. const showModal = (
  369. title: string,
  370. item: ProxiwashMachineType,
  371. isDryer: boolean
  372. ) => {
  373. setModalCurrentDisplayItem(getModalContent(title, item, isDryer));
  374. if (modalRef.current) {
  375. modalRef.current.open();
  376. }
  377. };
  378. /**
  379. * Adds the given notifications associated to a machine ID to the watchlist, and saves the array to the preferences
  380. *
  381. * @param machine
  382. */
  383. const saveNotificationToState = (machine: ProxiwashMachineType) => {
  384. let data = [...machinesWatched];
  385. data.push(machine);
  386. saveNewWatchedList(data);
  387. };
  388. /**
  389. * Removes the given index from the watchlist array and saves it to preferences
  390. *
  391. * @param selectedMachine
  392. */
  393. const removeNotificationFromState = (
  394. selectedMachine: ProxiwashMachineType
  395. ) => {
  396. const newList = machinesWatched.filter(
  397. (m) => m.number !== selectedMachine.number
  398. );
  399. saveNewWatchedList(newList);
  400. };
  401. const saveNewWatchedList = (list: Array<ProxiwashMachineType>) => {
  402. updatePreferences(ProxiwashPreferenceKeys.proxiwashWatchedMachines, list);
  403. };
  404. const renderListHeaderComponent = (
  405. data: FetchedDataType | undefined,
  406. _loading: boolean,
  407. lastRefreshDate: Date | undefined
  408. ) => {
  409. if (data) {
  410. return (
  411. <ProximoListHeader date={lastRefreshDate} selectedWash={selectedWash} />
  412. );
  413. } else {
  414. return null;
  415. }
  416. };
  417. let data: LaundromatType;
  418. switch (selectedWash) {
  419. case 'tripodeB':
  420. data = ProxiwashConstants.tripodeB;
  421. break;
  422. default:
  423. data = ProxiwashConstants.washinsa;
  424. }
  425. return (
  426. <View style={GENERAL_STYLES.flex}>
  427. <View style={styles.container}>
  428. <WebSectionList
  429. request={() => readData<FetchedDataType>(data.url)}
  430. createDataset={createDataset}
  431. renderItem={getRenderItem}
  432. renderSectionHeader={getRenderSectionHeader}
  433. autoRefreshTime={REFRESH_TIME}
  434. refreshOnFocus={true}
  435. extraData={machinesWatched.length}
  436. renderListHeaderComponent={renderListHeaderComponent}
  437. refresh={refresh}
  438. onFinish={() => setRefresh(false)}
  439. />
  440. </View>
  441. <MascotPopup
  442. title={i18n.t('screens.proxiwash.mascotDialog.title')}
  443. message={i18n.t('screens.proxiwash.mascotDialog.message')}
  444. icon="information"
  445. buttons={{
  446. action: {
  447. message: i18n.t('screens.proxiwash.mascotDialog.ok'),
  448. icon: 'cog',
  449. onPress: () => navigation.navigate('settings'),
  450. },
  451. cancel: {
  452. message: i18n.t('screens.proxiwash.mascotDialog.cancel'),
  453. icon: 'close',
  454. },
  455. }}
  456. emotion={MASCOT_STYLE.NORMAL}
  457. />
  458. <CustomModal ref={modalRef}>{modalCurrentDisplayItem}</CustomModal>
  459. </View>
  460. );
  461. }
  462. export default ProxiwashScreen;