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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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={'switch'}
  124. iconName={'swap-horizontal'}
  125. onPress={() => navigation.navigate('settings')}
  126. />
  127. <Item
  128. title={'information'}
  129. iconName={'information'}
  130. onPress={() => navigation.navigate('proxiwash-about')}
  131. />
  132. </MaterialHeaderButtons>
  133. ),
  134. });
  135. }, [navigation]);
  136. useFocusEffect(
  137. useCallback(() => {
  138. const selected = AsyncStorageManager.getString(
  139. AsyncStorageManager.PREFERENCES.selectedWash.key
  140. ) as 'tripodeB' | 'washinsa';
  141. if (selected !== selectedWash) {
  142. setSelectedWash(selected);
  143. }
  144. }, [selectedWash])
  145. );
  146. /**
  147. * Callback used when the user clicks on enable notifications for a machine
  148. *
  149. * @param machine The machine to set notifications for
  150. */
  151. const onSetupNotificationsPress = (machine: ProxiwashMachineType) => {
  152. if (modalRef.current) {
  153. modalRef.current.close();
  154. }
  155. setupNotifications(machine);
  156. };
  157. /**
  158. * Generates the modal content.
  159. * This shows information for the given machine.
  160. *
  161. * @param title The title to use
  162. * @param item The item to display information for in the modal
  163. * @param isDryer True if the given item is a dryer
  164. * @return {*}
  165. */
  166. const getModalContent = (
  167. title: string,
  168. item: ProxiwashMachineType,
  169. isDryer: boolean
  170. ) => {
  171. let button: { text: string; icon: string; onPress: () => void } | undefined;
  172. let message = modalStateStrings[item.state];
  173. const onPress = () => onSetupNotificationsPress(item);
  174. if (item.state === MachineStates.RUNNING) {
  175. let remainingTime = parseInt(item.remainingTime, 10);
  176. if (remainingTime < 0) {
  177. remainingTime = 0;
  178. }
  179. button = {
  180. text: isMachineWatched(item, machinesWatched)
  181. ? i18n.t('screens.proxiwash.modal.disableNotifications')
  182. : i18n.t('screens.proxiwash.modal.enableNotifications'),
  183. icon: '',
  184. onPress: onPress,
  185. };
  186. message = i18n.t('screens.proxiwash.modal.running', {
  187. start: item.startTime,
  188. end: item.endTime,
  189. remaining: remainingTime,
  190. program: item.program,
  191. });
  192. }
  193. return (
  194. <View style={styles.modalContainer}>
  195. <Card.Title
  196. title={title}
  197. left={() => (
  198. <Avatar.Icon
  199. icon={isDryer ? 'tumble-dryer' : 'washing-machine'}
  200. color={theme.colors.text}
  201. style={styles.icon}
  202. />
  203. )}
  204. />
  205. <Card.Content>
  206. <Text>{message}</Text>
  207. </Card.Content>
  208. {button ? (
  209. <Card.Actions>
  210. <Button
  211. icon={button.icon}
  212. mode="contained"
  213. onPress={button.onPress}
  214. style={GENERAL_STYLES.centerHorizontal}
  215. >
  216. {button.text}
  217. </Button>
  218. </Card.Actions>
  219. ) : null}
  220. </View>
  221. );
  222. };
  223. /**
  224. * Gets the section render item
  225. *
  226. * @param section The section to render
  227. * @return {*}
  228. */
  229. const getRenderSectionHeader = ({
  230. section,
  231. }: {
  232. section: SectionListData<ProxiwashMachineType>;
  233. }) => {
  234. const isDryer = section.title === i18n.t('screens.proxiwash.dryers');
  235. const nbAvailable = getMachineAvailableNumber(section.data);
  236. return (
  237. <ProxiwashSectionHeader
  238. title={section.title}
  239. nbAvailable={nbAvailable}
  240. isDryer={isDryer}
  241. />
  242. );
  243. };
  244. /**
  245. * Gets the list item to be rendered
  246. *
  247. * @param item The object containing the item's FetchedData
  248. * @param section The object describing the current SectionList section
  249. * @returns {React.Node}
  250. */
  251. const getRenderItem = (
  252. data: SectionListRenderItemInfo<ProxiwashMachineType>
  253. ) => {
  254. const isDryer = data.section.title === i18n.t('screens.proxiwash.dryers');
  255. return (
  256. <ProxiwashListItem
  257. item={data.item}
  258. onPress={showModal}
  259. isWatched={isMachineWatched(data.item, machinesWatched)}
  260. isDryer={isDryer}
  261. height={LIST_ITEM_HEIGHT}
  262. />
  263. );
  264. };
  265. /**
  266. * Extracts the key for the given item
  267. *
  268. * @param item The item to extract the key from
  269. * @return {*} The extracted key
  270. */
  271. const getKeyExtractor = (item: ProxiwashMachineType): string => item.number;
  272. /**
  273. * Setups notifications for the machine with the given ID.
  274. * One notification will be sent at the end of the program.
  275. * Another will be send a few minutes before the end, based on the value of reminderNotifTime
  276. *
  277. * @param machine The machine to watch
  278. */
  279. const setupNotifications = (machine: ProxiwashMachineType) => {
  280. if (!isMachineWatched(machine, machinesWatched)) {
  281. setupMachineNotification(
  282. machine.number,
  283. true,
  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 !== machinesWatched) {
  331. setMachinesWatched(machinesWatched);
  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. setMachinesWatched(list);
  393. AsyncStorageManager.set(
  394. AsyncStorageManager.PREFERENCES.proxiwashWatchedMachines.key,
  395. list
  396. );
  397. };
  398. const renderListHeaderComponent = (
  399. _data: FetchedDataType | undefined,
  400. loading: boolean,
  401. _refreshData: (newRequest?: () => Promise<FetchedDataType>) => void,
  402. status: REQUEST_STATUS
  403. ) => {
  404. const success = status === REQUEST_STATUS.SUCCESS;
  405. if (success && !loading) {
  406. lastrefreshDate.current = new Date();
  407. }
  408. return (
  409. <ProximoListHeader
  410. date={lastrefreshDate.current}
  411. selectedWash={selectedWash}
  412. />
  413. );
  414. };
  415. let data: LaundromatType;
  416. switch (selectedWash) {
  417. case 'tripodeB':
  418. data = ProxiwashConstants.tripodeB;
  419. break;
  420. default:
  421. data = ProxiwashConstants.washinsa;
  422. }
  423. return (
  424. <View style={GENERAL_STYLES.flex}>
  425. <View style={styles.container}>
  426. <WebSectionList
  427. request={() => readData<FetchedDataType>(data.url)}
  428. createDataset={createDataset}
  429. renderItem={getRenderItem}
  430. renderSectionHeader={getRenderSectionHeader}
  431. autoRefreshTime={REFRESH_TIME}
  432. refreshOnFocus={true}
  433. extraData={machinesWatched.length}
  434. renderListHeaderComponent={renderListHeaderComponent}
  435. />
  436. </View>
  437. <MascotPopup
  438. prefKey={AsyncStorageManager.PREFERENCES.proxiwashShowMascot.key}
  439. title={i18n.t('screens.proxiwash.mascotDialog.title')}
  440. message={i18n.t('screens.proxiwash.mascotDialog.message')}
  441. icon="information"
  442. buttons={{
  443. action: {
  444. message: i18n.t('screens.proxiwash.mascotDialog.ok'),
  445. icon: 'cog',
  446. onPress: () => navigation.navigate('settings'),
  447. },
  448. cancel: {
  449. message: i18n.t('screens.proxiwash.mascotDialog.cancel'),
  450. icon: 'close',
  451. },
  452. }}
  453. emotion={MASCOT_STYLE.NORMAL}
  454. />
  455. <CustomModal ref={modalRef}>{modalCurrentDisplayItem}</CustomModal>
  456. </View>
  457. );
  458. }
  459. export default ProxiwashScreen;