-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScreenLockMode.js
More file actions
287 lines (263 loc) · 8.63 KB
/
ScreenLockMode.js
File metadata and controls
287 lines (263 loc) · 8.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import React, { useState, useEffect, useRef } from 'react';
import { AppState, View, Text, StyleSheet, TextInput, TouchableOpacity, Alert, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { auth, db } from './firebase';
import { collection, query, where, getDocs, getDoc, doc, updateDoc } from 'firebase/firestore';
const ScreenLockScreen = () => {
const [time, setTime] = useState('');
const [countdown, setCountdown] = useState(0);
const [coinBalance, setCoinBalance] = useState(0);
const [earnedCoins, setEarnedCoins] = useState(0);
const [isQuitting, setIsQuitting] = useState(false);
const [isAppInBackground, setIsAppInBackground] = useState(false);
const navigation = useNavigation();
const appState = useRef(AppState.currentState);
useEffect(() => {
let timer;
if (countdown > 0) {
timer = setInterval(() => {
setCountdown((prevCountdown) => prevCountdown - 1);
}, 1000);
} else if (countdown === 0 && earnedCoins > 0 && !isQuitting) {
updateCoinBalance(earnedCoins);
updateTimeBalance(earnedCoins);
Alert.alert('Timer Completed', `You earned ${earnedCoins} coins!`);
}
return () => {
clearInterval(timer);
};
}, [countdown]);
useEffect(() => {
// Subscribe to AppState changes when the component mounts
const handleAppStateChange = (nextAppState) => {
appState.current = nextAppState;
if (nextAppState === 'background') {
// App is in the background
setIsAppInBackground(true);
} else {
// App is in the foreground or inactive
setIsAppInBackground(false);
}
};
AppState.addEventListener('change', handleAppStateChange);
return () => {
AppState.removeEventListener('change', handleAppStateChange);
};
}, []);
useEffect(() => {
if (!isAppInBackground) {
// If the app is not in the background, check if the countdown is active and show the alert
if (countdown > 0) {
navigation.goBack();
Alert.alert('You have attempted to exit the app!', 'We are disappointed in you.',
[{ text: 'Sorry', style: 'destructive', onPress: handleQuitConfirmed },]);
}
}
}, [isAppInBackground]);
const handleStartCountdown = () => {
const parsedTime = parseInt(time);
if (isNaN(parsedTime) || parsedTime <= 0) {
Alert.alert('Invalid Time', 'Please enter a valid time in minutes.');
return;
}
setTime('');
setCountdown(parsedTime * 60);
setEarnedCoins(parsedTime); // Set the earned coins to the parsedTime (1 coin per minute)
setIsQuitting(false); // Reset the quitting flag
};
const handleQuitCountdown = () => {
Alert.alert(
'Quit Screen Lock Mode',
'Are you sure you want to quit the Screen Lock Mode?',
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Quit', style: 'destructive', onPress: handleQuitConfirmed },
]
);
};
const handleQuitConfirmed = () => {
setIsQuitting(true);
setCountdown(0);
};
const handleBackButton = () => {
navigation.goBack();
};
const formatTime = (seconds) => {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
};
const updateCoinBalance = async (earnedCoins) => {
try {
const userId = auth.currentUser?.uid; // Get the currently authenticated user's ID
const usersCollectionRef = collection(db, 'users');
const querySnapshot = await getDocs(query(usersCollectionRef, where('userId', '==', userId)));
if (!querySnapshot.empty) {
const documentSnapshot = querySnapshot.docs[0];
const userDocRef = doc(db, 'users', documentSnapshot.id);
const userDocSnap = await getDoc(userDocRef);
if (userDocSnap.exists()) {
const userData = userDocSnap.data();
const currentCoins = userData.coins || 0;
const currentTotalCoins = userData.totalcoinsever || 0;
const newBalance = currentCoins + earnedCoins;
const newCurrentTotal = currentTotalCoins + earnedCoins;
console.log(userDocRef);
await updateDoc(userDocRef, { coins: newBalance });
await updateDoc(userDocRef, { totalcoinsever: newCurrentTotal });
console.log(newBalance);
console.log('Coin balance updated successfully.');
}
}
} catch (error) {
console.error('Error updating coin balance:', error);
}
};
const updateTimeBalance = async (earnedCoins) => {
try {
const userId = auth.currentUser?.uid; // Get the currently authenticated user's ID
const usersCollectionRef = collection(db, 'users');
const querySnapshot = await getDocs(query(usersCollectionRef, where('userId', '==', userId)));
if (!querySnapshot.empty) {
const documentSnapshot = querySnapshot.docs[0];
const userDocRef = doc(db, 'users', documentSnapshot.id);
const userDocSnap = await getDoc(userDocRef);
if (userDocSnap.exists()) {
const userData = userDocSnap.data();
const mostTime = userData.mosttimeever || 0;
if ((mostTime) < earnedCoins) {
console.log(userDocRef);
await updateDoc(userDocRef, { mosttimeever: earnedCoins });
}
}
}
} catch (error) {
console.error('Error updating coin balance:', error);
}
};
return (
<View style={styles.container}>
{countdown === 0 && (
<TouchableOpacity style={styles.backButton} onPress={handleBackButton}>
<Text style={styles.backButtonText}>Back</Text>
</TouchableOpacity>
)}
<Image source={require('./assets/ORBIMG10.png')} style={styles.lockIcon} />
<Text style={styles.heading}>Lock your phone!</Text>
<Text style={styles.subText}>Please enter the amount of time (in mins) to lock your phone for:</Text>
<View style={styles.timerContainer}>
{countdown > 0 ? (
<Text style={styles.timer}>{formatTime(countdown)}</Text>
) : (
<TextInput
style={styles.input}
value={time}
onChangeText={setTime}
keyboardType="default"
textAlign="center"
fontSize={48}
/>
)}
</View>
{countdown > 0 ? (
<TouchableOpacity style={styles.buttonGreen} onPress={handleQuitCountdown}>
<Text style={styles.buttonText}>Quit</Text>
</TouchableOpacity>
) : (
<TouchableOpacity style={styles.buttonGreen} onPress={handleStartCountdown}>
<Text style={styles.buttonText}>Start</Text>
</TouchableOpacity>
)}
{countdown > 0 && (
<View style={styles.coinBalanceContainer}>
<Text style={styles.coinBalanceText}>Coins to be earned: {earnedCoins}</Text>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#121212',
justifyContent: 'center',
alignItems: 'center',
},
lockIcon: {
width: 200,
height: 200,
resizeMode: 'contain',
marginBottom: -16,
},
backButton: {
position: 'absolute',
top: 40,
left: 16,
zIndex: 1,
},
backButtonText: {
fontSize: 18,
fontWeight: 'bold',
color: '#BBB', // Light gray color for back button text in dark mode
},
heading: {
fontSize: 32,
fontWeight: 'bold',
marginBottom: 16,
color: '#FFF',
},
subText: {
fontSize: 16,
marginLeft: 16,
marginRight: 16,
marginBottom: 32,
color: '#FFF',
textAlign: 'center',
},
timerContainer: {
marginBottom: 32,
},
timer: {
fontSize: 48,
fontWeight: 'bold',
color: '#FFF',
},
input: {
width: 200,
height: 80,
backgroundColor: '#121212',
color: '#FFF',
fontSize: 48,
fontWeight: 'bold',
borderWidth: 0,
borderBottomWidth: 2,
borderBottomColor: '#FFF',
textAlign: 'center',
paddingBottom: 8,
marginBottom: 32,
},
buttonGreen: {
marginTop: 10,
paddingHorizontal: 16,
paddingVertical: 12,
backgroundColor: '#006400', // Duller green color for buttons
borderRadius: 8,
width: '20%', // Set a fixed width for the buttons
justifyContent: 'center', // Center the text inside the button
alignItems: 'center', // Center the text inside the button
},
buttonText: {
fontSize: 16,
fontWeight: 'bold',
color: '#FFF', // White text color for buttons in dark mode
},
coinBalanceContainer: {
marginTop: 16,
},
coinBalanceText: {
fontSize: 18,
fontWeight: 'bold',
color: 'white',
},
});
export default ScreenLockScreen;