2020-09-11 21:23:26 +00:00
|
|
|
import AsyncStorage from '@react-native-community/async-storage';
|
|
|
|
import {parse} from 'date-fns';
|
|
|
|
import React, {ReactElement, useEffect, useState} from 'react';
|
|
|
|
import {View} from 'react-native';
|
|
|
|
import {Title} from 'react-native-paper';
|
|
|
|
import {dateFormat} from '../config/default';
|
|
|
|
import {SyncProps} from '../models/ElementProps';
|
|
|
|
import {LineCount} from '../models/LineCount';
|
|
|
|
import {Sample} from '../models/Sample';
|
|
|
|
import {CancelButton} from './Common';
|
|
|
|
import {styles} from './Styles';
|
|
|
|
import * as firebase from 'firebase';
|
|
|
|
import 'firebase/firestore';
|
|
|
|
|
|
|
|
export const sendDataToFirebase = async (newData: Array<Sample | LineCount>, collection: firebase.firestore.CollectionReference) => {
|
|
|
|
const writes = newData.map((s: Sample | LineCount) => collection.doc(s.id).set(s));
|
|
|
|
await Promise.all(writes);
|
|
|
|
}
|
|
|
|
|
|
|
|
export const SyncMessage = (props: SyncProps): ReactElement => {
|
|
|
|
const [syncStatus, setSyncStatus] = useState<string>('Syncing data...');
|
|
|
|
|
|
|
|
useEffect(() => {
|
2020-09-13 12:08:27 +00:00
|
|
|
// TODO: Alternatively, set up a timer that periodically syncs data with the database.
|
2020-09-11 21:23:26 +00:00
|
|
|
|
2020-09-13 12:08:27 +00:00
|
|
|
// Detect when user is online. If online, sync data with Firebase.
|
2020-09-11 21:23:26 +00:00
|
|
|
if (props.isConnected) {
|
2020-09-13 12:08:27 +00:00
|
|
|
// Get the collection subscription
|
|
|
|
const unsubscribe = props.samplesCollection.onSnapshot(q => {}, e => {});
|
|
|
|
|
|
|
|
// Upload any changes to Firebase
|
2020-09-11 21:23:26 +00:00
|
|
|
AsyncStorage.getAllKeys().then(keys => {
|
|
|
|
const newSamples = keys
|
|
|
|
.filter(s => /^[\d]{9}-[\d]{12}-[\d]{4}$/.test(s))
|
|
|
|
.map(s => {
|
|
|
|
const propsArray = s.split('-');
|
|
|
|
return {
|
|
|
|
id: s,
|
|
|
|
barcodeId: propsArray[0],
|
|
|
|
createdAt: parse(propsArray[1], dateFormat, new Date()),
|
|
|
|
locationId: propsArray[2],
|
|
|
|
} as Sample;
|
|
|
|
});
|
|
|
|
|
|
|
|
sendDataToFirebase(newSamples, props.samplesCollection).then(() => {
|
2020-09-13 12:08:27 +00:00
|
|
|
// TODO: Delete stored keys in AsyncStorage
|
|
|
|
|
2020-09-11 21:23:26 +00:00
|
|
|
setSyncStatus('Data synced.');
|
|
|
|
props.onSync();
|
|
|
|
});
|
|
|
|
});
|
2020-09-13 12:08:27 +00:00
|
|
|
|
|
|
|
return () => unsubscribe();
|
2020-09-11 21:23:26 +00:00
|
|
|
} else {
|
2020-09-13 12:08:27 +00:00
|
|
|
// If not online, just go home.
|
2020-09-11 21:23:26 +00:00
|
|
|
setSyncStatus('Device is not online. Skipping sync...');
|
|
|
|
props.onCancel();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return <View style={styles.container}>
|
|
|
|
<View style={styles.centerMiddle}>
|
|
|
|
<Title style={styles.heading}>{syncStatus}</Title>
|
|
|
|
<CancelButton onClicked={props.onCancel} />
|
|
|
|
</View>
|
|
|
|
</View>;
|
|
|
|
}
|