import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:geoflutterfire/geoflutterfire.dart'; import 'dart:math'; import '../Services/AuthService.dart'; import '../Services/logged_in_user.dart'; class ChallengesUtils { static final geo = Geoflutterfire(); static final _firestore = FirebaseFirestore.instance; static generateChallengeIfNeeded() async { if (await shouldGenerateChallenge()) { generateChallenge(); } } static Future shouldGenerateChallenge() async { LoggedInUser? user = await AuthenticationServices.getCurrentUser(); DateTime now = DateTime.now(); DateTime today = DateTime(now.year, now.month, now.day); DateTime lastMonday = today.subtract(Duration(days: today.weekday - 1)); int secondsSinceEpoch = lastMonday.millisecondsSinceEpoch ~/ 1000; final dif = secondsSinceEpoch - user!.lastChallengeDate.seconds; return Future.value(dif / 3600 / 24 > 7); } static void generateChallenge() async { LoggedInUser? user = await AuthenticationServices.getCurrentUser(); Query> places = _firestore.collection('Places'); double innerRadius = 1; double outerRadius = 2.5; String randomPlaceID = ''; Stream> possiblePlaces = geo.collection(collectionRef: places).within( center: geo.point(latitude: user!.address.latitude, longitude: user.address.longitude), radius: outerRadius, field: 'location', strictMode: true); Stream> placesTooClose = geo.collection(collectionRef: places).within( center: geo.point(latitude: user.address.latitude, longitude: user.address.longitude), radius: innerRadius, field: 'location', strictMode: true); List> possiblePlacesList = await possiblePlaces.first; List> placesTooCloseList = await placesTooClose.first; final ids = {}; for (DocumentSnapshot element in placesTooCloseList) { ids.add(element.id); } possiblePlacesList.retainWhere((element) => !ids.contains(element.id)); int numOfPlaces = possiblePlacesList.length; randomPlaceID = possiblePlacesList[Random().nextInt(numOfPlaces)].id; AuthenticationServices.user!.weeklyPlace = _firestore.collection('Places').doc(randomPlaceID); _firestore.collection("profileInfo").doc(FirebaseAuth.instance.currentUser?.uid).update({ 'weekly_place': _firestore.collection('Places').doc(randomPlaceID), 'last_challenge_date': Timestamp.now(), }); } }