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

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