| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- 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<bool> 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<Map<String, dynamic>> places = _firestore.collection('Places');
- double innerRadius = 1;
- double outerRadius = 2.5;
- String randomPlaceID = '';
- Stream<List<DocumentSnapshot>> possiblePlaces = geo.collection(collectionRef: places).within(
- center: geo.point(latitude: user!.address.latitude, longitude: user.address.longitude),
- radius: outerRadius,
- field: 'location',
- strictMode: true);
- Stream<List<DocumentSnapshot>> placesTooClose = geo.collection(collectionRef: places).within(
- center: geo.point(latitude: user.address.latitude, longitude: user.address.longitude),
- radius: innerRadius,
- field: 'location',
- strictMode: true);
- List<DocumentSnapshot<Object?>> possiblePlacesList = await possiblePlaces.first;
- List<DocumentSnapshot<Object?>> placesTooCloseList = await placesTooClose.first;
- final ids = <String>{};
- for (DocumentSnapshot<Object?> 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(),
- });
- }
- }
|