| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- import 'package:cloud_firestore/cloud_firestore.dart';
- import 'dart:math';
- class ChallengesUtils {
- static Future<DocumentSnapshot<Map<String, dynamic>>> getChallenge() async {
- Future<DocumentSnapshot<Map<String, dynamic>>> challenge;
- if(await shouldGenerateChallenge()){
- challenge = generateChallenge();
- } else {
- final user = FirebaseFirestore.instance
- .collection('Users')
- .doc('tlmysIvwTBaoZKWqBofx');
- challenge = user.get().then((value) => value.get('weekly_place').get());
- }
- return challenge;
- }
- static Future<bool> shouldGenerateChallenge() async {
- final user = FirebaseFirestore.instance
- .collection('Users')
- .doc('tlmysIvwTBaoZKWqBofx');
- DateTime now = DateTime.now();
- int secondsSinceEpoch = now.millisecondsSinceEpoch ~/ 1000;
- bool shouldGenerate = await user.get().then((value) {
- final dif = secondsSinceEpoch - value.get('last_challenge_date').seconds;
- return dif / 3600 / 24 > 7;
- });
- return Future.value(shouldGenerate);
- }
- static Future<DocumentSnapshot<Map<String, dynamic>>> generateChallenge() {
- final user = FirebaseFirestore.instance
- .collection('Users')
- .doc('tlmysIvwTBaoZKWqBofx');
- return user.get().then((value) {
- double lat = 0.0144927536231884;
- double lon = 0.0181818181818182;
- double userLat = value.get('address').latitude;
- double userLon = value.get('address').longitude;
- double lowerLat = userLat - (lat * 5);
- double lowerLon = userLon - (lon * 5);
- double upperLat = userLat + (lat * 5);
- double upperLon = userLon + (lon * 5);
- GeoPoint lesserGeoPoint = GeoPoint(lowerLat, lowerLon);
- GeoPoint greaterGeoPoint = GeoPoint(upperLat, upperLon);
- return FirebaseFirestore.instance
- .collection('Places')
- .where('location', isGreaterThan: lesserGeoPoint)
- .where('location', isLessThan: greaterGeoPoint)
- .get()
- .then((snapshot) {
- int numOfPlaces = snapshot.docs.length;
- String id = snapshot.docs[Random().nextInt(numOfPlaces)].id;
- print('updating');
- user.update({
- 'weekly_place':
- FirebaseFirestore.instance.collection('Places').doc(id),
- 'last_challenge_date': Timestamp.now(),
- });
- return FirebaseFirestore.instance.collection('Places').doc(id).get();
- });
- });
- }
- }
|