challenges_utils.dart 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'package:cloud_firestore/cloud_firestore.dart';
  2. import 'package:firebase_auth/firebase_auth.dart';
  3. import 'package:geoflutterfire/geoflutterfire.dart';
  4. import 'dart:math';
  5. import '../Services/AuthService.dart';
  6. import '../Services/logged_in_user.dart';
  7. class ChallengesUtils {
  8. static final geo = Geoflutterfire();
  9. static final _firestore = FirebaseFirestore.instance;
  10. static generateChallengeIfNeeded() async {
  11. if (await shouldGenerateChallenge()) {
  12. generateChallenge();
  13. }
  14. }
  15. static Future<bool> shouldGenerateChallenge() async {
  16. LoggedInUser? user = await AuthenticationServices.getCurrentUser();
  17. DateTime now = DateTime.now();
  18. DateTime today = DateTime(now.year, now.month, now.day);
  19. DateTime lastMonday = today.subtract(Duration(days: today.weekday - 1));
  20. int secondsSinceEpoch = lastMonday.millisecondsSinceEpoch ~/ 1000;
  21. final dif = secondsSinceEpoch - user!.lastChallengeDate.seconds;
  22. return Future.value(dif / 3600 / 24 > 7);
  23. }
  24. static void generateChallenge() async {
  25. LoggedInUser? user = await AuthenticationServices.getCurrentUser();
  26. Query<Map<String, dynamic>> places = _firestore.collection('Places');
  27. double innerRadius = 1;
  28. double outerRadius = 2.5;
  29. String randomPlaceID = '';
  30. Stream<List<DocumentSnapshot>> possiblePlaces = geo.collection(collectionRef: places).within(
  31. center: geo.point(latitude: user!.address.latitude, longitude: user.address.longitude),
  32. radius: outerRadius,
  33. field: 'location',
  34. strictMode: true);
  35. Stream<List<DocumentSnapshot>> placesTooClose = geo.collection(collectionRef: places).within(
  36. center: geo.point(latitude: user.address.latitude, longitude: user.address.longitude),
  37. radius: innerRadius,
  38. field: 'location',
  39. strictMode: true);
  40. List<DocumentSnapshot<Object?>> possiblePlacesList = await possiblePlaces.first;
  41. List<DocumentSnapshot<Object?>> placesTooCloseList = await placesTooClose.first;
  42. final ids = <String>{};
  43. for (DocumentSnapshot<Object?> element in placesTooCloseList) {
  44. ids.add(element.id);
  45. }
  46. possiblePlacesList.retainWhere((element) => !ids.contains(element.id));
  47. int numOfPlaces = possiblePlacesList.length;
  48. randomPlaceID = possiblePlacesList[Random().nextInt(numOfPlaces)].id;
  49. AuthenticationServices.user!.weeklyPlace = _firestore.collection('Places').doc(randomPlaceID);
  50. _firestore.collection("profileInfo").doc(FirebaseAuth.instance.currentUser?.uid).update({
  51. 'weekly_place': _firestore.collection('Places').doc(randomPlaceID),
  52. 'last_challenge_date': Timestamp.now(),
  53. });
  54. }
  55. }