| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- import 'package:cloud_firestore/cloud_firestore.dart';
- import 'package:geoflutterfire/geoflutterfire.dart';
- import 'dart:math';
- class ChallengesUtils {
- static final geo = Geoflutterfire();
- static final _firestore = FirebaseFirestore.instance;
- static Future<DocumentSnapshot<Map<String, dynamic>>> getChallenge() async {
- Future<DocumentSnapshot<Map<String, dynamic>>> challenge;
- if (await shouldGenerateChallenge()) {
- challenge = generateChallenge();
- } else {
- final user = _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx');
- challenge = user.get().then((value) => value.get('weekly_place').get());
- }
- return challenge;
- }
- static Future<bool> shouldGenerateChallenge() async {
- final user = _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx');
- 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;
- 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() async {
- final user = await _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx').get();
- Query<Map<String, dynamic>> places = _firestore.collection('Places');
- double innerRadius = 3;
- double outerRadius = 5;
- String randomPlaceID = '';
- Stream<List<DocumentSnapshot>> possiblePlaces = geo.collection(collectionRef: places).within(
- center: geo.point(latitude: user.get('address').latitude, longitude: user.get('address').longitude),
- radius: outerRadius,
- field: 'location',
- strictMode: true);
- Stream<List<DocumentSnapshot>> placesTooClose = geo.collection(collectionRef: places).within(
- center: geo.point(latitude: user.get('address').latitude, longitude: user.get('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;
- _firestore.collection('Users').doc('tlmysIvwTBaoZKWqBofx').update({
- 'weekly_place': _firestore.collection('Places').doc(randomPlaceID),
- 'last_challenge_date': Timestamp.now(),
- });
- return _firestore.collection('Places').doc(randomPlaceID).get();
- }
- }
|