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

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