Files
rog_app/lib/pages/destination/destination_controller.dart
2023-09-15 18:11:13 +05:30

1118 lines
37 KiB
Dart

import 'dart:io';
import 'package:camera_camera/camera_camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:geojson/geojson.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:latlong2/latlong.dart';
import 'package:rogapp/main.dart';
import 'package:rogapp/model/destination.dart';
import 'package:rogapp/pages/camera/camera_page.dart';
import 'package:rogapp/pages/index/index_controller.dart';
import 'package:rogapp/routes/app_pages.dart';
import 'package:rogapp/services/destination_service.dart';
import 'package:rogapp/services/external_service.dart';
import 'package:rogapp/services/location_service.dart';
import 'package:rogapp/services/maxtrix_service.dart';
import 'package:rogapp/services/perfecture_service.dart';
import 'package:rogapp/utils/database_helper.dart';
import 'package:rogapp/widgets/bottom_sheet_new.dart';
import 'dart:async';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:gallery_saver/gallery_saver.dart';
class DestinationController extends GetxController {
late LocationSettings locationSettings;
var destinationCount = 0.obs;
List<Destination> destinations = <Destination>[].obs;
double current_lat = 0.0;
double current_lon = 0.0;
bool skip_10s = false;
List<Destination> currentSelectedDestinations = <Destination>[].obs;
var is_in_checkin = false.obs;
var is_in_rog = false.obs;
var is_at_start = false.obs;
var is_at_goal = false.obs;
var is_photo_shoot = false.obs;
DateTime last_goal_at = DateTime.now().subtract(const Duration(days: 1));
//List<Rogaining> rogainings = <Rogaining>[].obs;
bool checking_in = false;
var is_gps_selected = true.obs;
BuildContext? context;
List<String> gps = <String>["-- stating --"].obs;
List<String> locationPermission = <String>[" -- starting -- "].obs;
StreamSubscription<Position>? positionStream;
Timer? _GPStimer;
var travelMode = 0.obs;
bool skip_gps = false;
Map<String, dynamic> matrix = {};
final photos = <File>[].obs;
final IndexController indexController = Get.find<IndexController>();
Timer? _timer;
int _start = 0;
int chekcs = 0;
var rogaining_counted = false.obs;
String getFormatedTime(DateTime datetime) {
return DateFormat('yyyy-MM-dd HH:mm:ss').format(datetime);
}
Destination festuretoDestination(GeoJsonFeature fs) {
GeoJsonMultiPoint mp = fs.geometry as GeoJsonMultiPoint;
LatLng pt = LatLng(mp.geoSerie!.geoPoints[0].latitude,
mp.geoSerie!.geoPoints[0].longitude);
//print("----- ${indexController.currentFeature[0].properties} -----");
return Destination(
name: fs.properties!["location_name"],
sub_loc_id: fs.properties!["sub_loc_id"],
address: fs.properties!["address"],
phone: fs.properties!["phone"],
email: fs.properties!["email"],
webcontents: fs.properties!["webcontents"],
videos: fs.properties!["videos"],
category: fs.properties!["category"],
series: 1,
lat: pt.latitude,
lon: pt.longitude,
location_id: fs.properties!["location_id"],
list_order: 1,
photos: fs.properties!["photos"],
checkin_radious: fs.properties!["checkin_radius"],
auto_checkin: fs.properties!["auto_checkin"] == true ? 1 : 0,
cp: fs.properties!["cp"],
checkin_point: fs.properties!["checkin_point"],
buy_point: fs.properties!["buy_point"],
selected: false,
checkedin: false,
hidden_location: fs.properties!["hidden_location"] == true ? 1 : 0);
}
Future<void> startTimerLocation(GeoJsonFeature fs, double distance) async {
print("---- in startTimer ----");
print("---- is in rog is ${is_in_rog} ----");
//skip_gps = true;
double checkinRadious = fs.properties!['checkin_radius'] ?? double.infinity;
if (checkinRadious >= distance) {
indexController.currentFeature.clear();
Destination d = festuretoDestination(fs);
print("----- destination lenght is ${destinations.length} -----");
// for (Destination de in destinations) {
// if (de.location_id == d.location_id) {
// d = de;
// break;
// }
// }
indexController.currentFeature.add(fs);
print("---- before calling startTimer ----");
await startTimer(d, distance);
return;
}
}
Future<void> startTimer(Destination d, double distance) async {
print("=== passed dest is ${d.location_id} ${d.checkedin} ====");
skip_gps = true;
print("---- in startTimer ----");
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> ds = await db.getDestinationByLatLon(d.lat!, d.lon!);
Destination? dss;
if (ds.isNotEmpty) {
dss = ds.first;
}
double checkinRadious = d.checkin_radious ?? double.infinity;
bool autoCheckin = d.auto_checkin == 0 ? false : true;
bool buyPoint = dss != null && dss.buy_point != null && dss.buy_point! > 0
? true
: false;
bool buyPointImageAdded =
dss != null && dss.buypoint_image != null ? true : false;
bool buyPointCanceled = dss != null && dss.buy_point != null && dss.buy_point == 0 ? true : false;
bool locationAlreadyCheckedIn =
ds.length > 0 && ds[0].checkedin == true ? true : false;
bool isuserLoggedIn = indexController.currentUser.isNotEmpty ? true : false;
//make current destination
print("---- checkin_radious $checkinRadious ----");
print("---- distance $distance ----");
if (checkinRadious >= distance) {
//currentSelectedDestinations.add(d);
indexController.currentDestinationFeature.clear();
indexController.currentDestinationFeature.add(d);
print(
"---- checked in as ${indexController.currentDestinationFeature[0].checkedin.toString()} ----");
} else {
skip_gps = false;
return;
}
if (is_photo_shoot.value == true) {
photos.clear();
await showModalBottomSheet(
constraints: BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) =>
CameraPage(destination: d))).whenComplete(() {
skip_gps = false;
chekcs = 0;
is_in_checkin.value = false;
});
return;
}
if (ds.isEmpty) {
print("----- in location popup cp - ${d.cp}----");
if (d.cp == -1 && DateTime.now().difference(last_goal_at).inHours >= 24) {
chekcs = 1;
//start
print("---- in start -----");
chekcs = 1;
is_in_checkin.value = true;
is_at_start.value = true;
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => BottomSheetNew(
destination: d,
))).whenComplete(() {
skip_gps = false;
chekcs = 0;
is_at_start.value = false;
is_in_checkin.value = false;
});
return;
} else if (is_in_rog.value == true && indexController.rog_mode == 1) {
print("----- in location popup checkin cp - ${d.cp}----");
chekcs = 2;
is_in_checkin.value = true;
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => BottomSheetNew(
destination: d,
))).whenComplete(() {
skip_gps = false;
chekcs = 0;
is_in_checkin.value = false;
});
return;
}
}
print("---- location checkin radious ${d.checkin_radious} ----");
print("---- already checked in $locationAlreadyCheckedIn ----");
if (checkinRadious >= distance &&
locationAlreadyCheckedIn == false &&
is_in_rog.value == true) {
if (autoCheckin) {
if (!checking_in) {
print(
"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ make checkin ${d.sub_loc_id}@@@@@@@@@@@");
makeCheckin(d, true, "");
if (d.cp != -1) {
rogaining_counted.value = true;
}
skip_gps = false;
}
return;
} else {
print("--- hidden loc ${d.hidden_location} ----");
// ask for checkin
if (d.hidden_location != null &&
d.hidden_location == 0 &&
is_in_rog.value == true &&
d.cp != -1) {
chekcs = 3;
is_in_checkin.value = true;
photos.clear();
print("--- calling checkin ---");
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
destination: d,
))).whenComplete(() {
skip_gps = false;
rogaining_counted.value = true;
chekcs = 0;
is_in_checkin.value = false;
});
return;
} else if (is_in_rog.value == true && d.cp != -1) {
chekcs = 4;
is_in_checkin.value = true;
await showMaterialModalBottomSheet(
expand: true,
context: Get.context!,
backgroundColor: Colors.transparent,
builder: (context) => BottomSheetNew(
destination: d,
)).whenComplete(() {
skip_gps = false;
chekcs = 0;
is_in_checkin.value = false;
});
return;
// showModalBottomSheet(context: Get.context!, isScrollControlled: true,
// builder:((context) => BottomSheetNew())
// ).whenComplete((){
// skip_gps = false;
// chekcs = 0;
// is_in_checkin.value = false;
// });
}
}
} else if (checkinRadious >= distance &&
locationAlreadyCheckedIn == true &&
buyPointImageAdded == false &&
ds.isNotEmpty &&
buyPoint == true &&
buyPointCanceled == false &&
is_in_rog.value == true) {
chekcs = 5;
is_in_checkin.value = true;
photos.clear();
print(
"--- open buy point ${buyPointImageAdded} ${d.buypoint_image} ----");
await showModalBottomSheet(
constraints: BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
buyPointPhoto: true,
destination: d,
dbDest: ds.first,
))).whenComplete(() {
skip_gps = false;
rogaining_counted.value = true;
chekcs = 0;
is_in_checkin.value = false;
});
return;
}
print("---- cp --- ${d.cp} -----");
print("--- at goal $is_at_goal ---");
print("--- rog counted $rogaining_counted ---");
print("--- loc already checked in $locationAlreadyCheckedIn ---");
print(
"==== date diff is ${DateTime.now().difference(last_goal_at).inHours} ====");
if (isuserLoggedIn &&
d.cp == -1 &&
locationAlreadyCheckedIn &&
skip_10s == false) {
//check for rogaining
if (is_at_goal.value == false && rogaining_counted.value) {
//goal
print("---- in goal -----");
chekcs = 5;
is_at_goal.value = true;
photos.clear();
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
destination: d,
))).whenComplete(() {
skip_gps = false;
chekcs = 0;
is_at_goal.value = false;
});
return;
} else if (is_in_rog.value == false &&
indexController.rog_mode == 1 &&
DateTime.now().difference(last_goal_at).inHours >= 24) {
//start
print("---- in start -----");
chekcs = 6;
is_at_start.value = true;
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => BottomSheetNew(
destination: d,
))).whenComplete(() {
print("----- finished start -------");
skip_gps = false;
chekcs = 0;
is_at_start.value = false;
});
return;
}
}
print("==== _chekcs $chekcs ====");
if (chekcs == 0) {
skip_gps = false;
}
return;
}
void resetRogaining() async {
print("----- resetting --------");
is_in_checkin.value = false;
is_in_rog.value = false;
is_at_start.value = false;
is_at_goal.value = false;
is_gps_selected.value = true;
skip_gps = false;
_start = 0;
chekcs = 0;
rogaining_counted.value = false;
DatabaseHelper db = DatabaseHelper.instance;
int? _latgoal = await db.latestGoal();
if (_latgoal != null) {
last_goal_at = DateTime.fromMicrosecondsSinceEpoch(_latgoal);
print("===== last goal : $last_goal_at =====");
}
//deleteDBDestinations();
// currentSelectedDestinations.forEach((element) {
// deleteDestination(element);
// });
}
void deleteAllDestinations() {
DatabaseHelper db = DatabaseHelper.instance;
db.deleteAllDestinations().then((value) {
PopulateDestinations();
startGPSTimer();
//startGame();
//initGPS();
});
}
void openCamera(BuildContext context, Destination? destination) {
photos.clear();
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => CameraCamera(
resolutionPreset: ResolutionPreset.medium,
onFile: (file) {
photos.add(file);
Navigator.pop(context);
print("----image file is : $file----");
//setState(() {});
},
)));
}
void getRoutePoints() {
indexController.routePoints = [];
indexController.routePointLenght.value = 0;
DestinationService.getDestinationLine(destinations, matrix)?.then((value) {
indexController.routePoints = value;
indexController.routePointLenght.value =
indexController.routePoints.length;
});
}
Future<Destination?> getDestinationForLatLong(double lat, double long) async {
for (final d in destinations) {
if (lat == d.lat && long == d.lon) {
return d;
}
}
return null;
}
Future<void> CallforCheckin(Destination d) async {
bool autoCheckin = d.auto_checkin == 0 ? false : true;
print("---- f- checkin ${d.sub_loc_id} ----");
if (autoCheckin) {
if (!checking_in) {
makeCheckin(d, true, "");
if (d.cp != -1) {
rogaining_counted.value = true;
}
}
} else {
print("--- hidden loc ${d.hidden_location} ----");
// ask for checkin
print("is rog ---- ${is_in_rog.value} ----");
if (d.hidden_location != null &&
d.hidden_location == 0 &&
is_in_rog.value == true &&
d.cp != -1) {
chekcs = 3;
is_in_checkin.value = true;
photos.clear();
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
manulaCheckin: true,
destination: d,
))).whenComplete(() async {
if (d.buy_point != null && d.buy_point! > 0) {
skip_gps = true;
photos.clear();
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> ds =
await db.getDestinationByLatLon(d.lat!, d.lon!);
Destination? dss;
if (ds.isNotEmpty) {
dss = ds.first;
}
await showModalBottomSheet(
constraints:
BoxConstraints.loose(Size(Get.width, Get.height * 0.75)),
context: Get.context!,
isScrollControlled: true,
builder: ((context) => CameraPage(
buyPointPhoto: true,
destination: d,
dbDest: dss,
))).whenComplete(() {
skip_gps = false;
rogaining_counted.value = true;
chekcs = 0;
is_in_checkin.value = false;
});
} else {
skip_gps = false;
chekcs = 0;
is_in_checkin.value = false;
}
});
} else {
Get.snackbar("始まっていない", "ロゲイニングを始める必要があります");
}
}
}
Future<void> checkForCheckin() async {
print("--- Start of checkForCheckin function ---");
try {
print("--- 000 ---- $skip_gps----");
await Future.delayed(const Duration(milliseconds: 2500));
final la = current_lat;
final ln = current_lon;
for (GeoJsonFeature fs in indexController.locations[0].collection) {
GeoJsonMultiPoint mp = fs.geometry as GeoJsonMultiPoint;
LatLng pt = LatLng(mp.geoSerie!.geoPoints[0].latitude,
mp.geoSerie!.geoPoints[0].longitude);
double latFs = pt.latitude;
double lonFs = pt.longitude;
var distanceFs = const Distance();
double distFs = distanceFs.as(
LengthUnit.Meter, LatLng(latFs, lonFs), LatLng(la, ln));
Destination des = festuretoDestination(fs);
if (distFs <= des.checkin_radious! && skip_gps == false) {
print("--- 789 ---- $skip_gps----");
//near a location
print("---- before call startTimerLocation ----");
await startTimerLocation(fs, distFs);
break;
}
}
print("--- 123 ---- $skip_gps----");
} catch (e) {
print("An error occurred: $e");
await checkForCheckin();
} finally {
print("--- End of checkForCheckin function, calling recursively ---");
await checkForCheckin();
}
}
// void checkForCheckin() async {
// final la = current_lat;
// final ln = current_lon;
// print("--- in checkForCheckin ----");
// // if (indexController.locations.isEmpty){
// // await Future.delayed(const Duration(seconds: 2));
// // checkForCheckin();
// // return;
// // }
// print("--- 123 ---- $skip_gps----");
// //check for location in bounds
// for (GeoJsonFeature fs in indexController.locations[0].collection) {
// try {
// await Future.delayed(const Duration(seconds: 2000));
// GeoJsonMultiPoint mp = fs.geometry as GeoJsonMultiPoint;
// LatLng pt = LatLng(mp.geoSerie!.geoPoints[0].latitude,
// mp.geoSerie!.geoPoints[0].longitude);
// print("--- 456 ---- $skip_gps----");
// double latFs = pt.latitude;
// double lonFs = pt.longitude;
// LatLng pFs = LatLng(latFs, lonFs);
// var distanceFs = const Distance();
// double distFs = distanceFs.as(
// LengthUnit.Meter, LatLng(latFs, lonFs), LatLng(la, ln));
// if (distFs <= 250 && skip_gps == false) {
// print("--- 789 ---- $skip_gps----");
// //near a location
// print("---- before call startTimerLocation ----");
// startTimerLocation(fs, distFs);
// }
// } catch (e) {
// print("----- error -----");
// } finally {
// print("--- 101112 ----");
// checkForCheckin();
// }
// }
// //await Future.delayed(const Duration(seconds: 3));
// }
void addToRogaining(double lat, double lon, int destinationId) async {
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> d = await db.getDestinationById(destinationId);
if (d.isEmpty) {
Destination df = festuretoDestination(indexController.currentFeature[0]);
print("--- made checkin ${df.location_id} ----");
makeCheckin(df, true, "");
}
is_in_rog.value = true;
saveGameState();
}
Future<void> cancelBuyPoint(Destination destination) async {
DatabaseHelper db = DatabaseHelper.instance;
await db.updateCancelBuyPoint(destination);
PopulateDestinations();
}
Future<void> makeBuyPoint(Destination destination, String imageurl) async {
DatabaseHelper db = DatabaseHelper.instance;
await db.updateBuyPoint(destination, imageurl);
PopulateDestinations();
await GallerySaver.saveImage(imageurl);
if (indexController.currentUser.isNotEmpty) {
double cpNum = destination.cp!;
int userId = indexController.currentUser[0]["user"]["id"];
//print("--- Pressed -----");
String _team = indexController.currentUser[0]["user"]['team_name'];
//print("--- _team : ${_team}-----");
String _event_code = indexController.currentUser[0]["user"]["event_code"];
//print("--- _event_code : ${_event_code}-----");
String _token = indexController.currentUser[0]["token"];
//print("--- _token : ${_token}-----");
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(now);
print("------ checkin event $_event_code ------");
ExternalService()
.makeCheckpoint(userId, _token, formattedDate, _team, cpNum.round(),
_event_code, imageurl)
.then((value) {
print("------Ext service check point $value ------");
});
}
}
Future<void> makeCheckin(
Destination destination, bool action, String imageurl) async {
print(
"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ressssss ${destination.sub_loc_id}@@@@@@@@@@@");
DatabaseHelper db = DatabaseHelper.instance;
List<Destination> ddd =
await db.getDestinationByLatLon(destination.lat!, destination.lon!);
if (ddd.isEmpty) {
destination.checkedin = true;
destination.checkin_image = imageurl;
await db.insertDestination(destination);
}
await GallerySaver.saveImage(imageurl);
PopulateDestinations();
/// post to NATNAT
if (indexController.currentUser.isNotEmpty) {
double cpNum = destination.cp!;
int userId = indexController.currentUser[0]["user"]["id"];
//print("--- Pressed -----");
String _team = indexController.currentUser[0]["user"]['team_name'];
//print("--- _team : ${_team}-----");
String _event_code = indexController.currentUser[0]["user"]["event_code"];
//print("--- _event_code : ${_event_code}-----");
String _token = indexController.currentUser[0]["token"];
//print("--- _token : ${_token}-----");
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(now);
print("------ checkin event $_event_code ------");
ExternalService()
.makeCheckpoint(userId, _token, formattedDate, _team, cpNum.round(),
_event_code, imageurl)
.then((value) {
print("------Ext service check point $value ------");
});
}
}
void initGPS() {
checkPermission();
PopulateDestinations();
//print("------ in iniit");
if (defaultTargetPlatform == TargetPlatform.android) {
locationSettings = AndroidSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 1,
forceLocationManager: true,
intervalDuration: const Duration(seconds: 3),
//(Optional) Set foreground notification config to keep the app alive
//when going to the background
foregroundNotificationConfig: const ForegroundNotificationConfig(
notificationText:
"Example app will continue to receive your location even when you aren't using it",
notificationTitle: "Running in Background",
enableWakeLock: true,
));
} else if (defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS) {
locationSettings = AppleSettings(
accuracy: LocationAccuracy.high,
activityType: ActivityType.fitness,
distanceFilter: 0,
pauseLocationUpdatesAutomatically: false,
// Only set to true if our app will be started up in the background.
showBackgroundLocationIndicator: true);
} else {
locationSettings = const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 0,
);
}
try {
positionStream =
Geolocator.getPositionStream(locationSettings: locationSettings)
.listen((Position? position) {
current_lat = position != null ? position.latitude : 0;
current_lon = position != null ? position.longitude : 0;
indexController.current_lat = position != null ? position.latitude : 0;
current_lon = position != null ? position.longitude : 0;
print(
"==== gps skip is : ${skip_gps.toString()}, selected is $is_gps_selected , $current_lat");
if (is_gps_selected.value) {
double czoom = indexController.rogMapController.zoom;
indexController.rogMapController
.move(LatLng(position!.latitude, position.longitude), czoom);
//String user_id = indexController.currentUser[0]["user"]["id"].toString();
//TrackingService.addTrack(user_id, position!.latitude, position.longitude).then((val){
//print("---- postion is ${position.latitude}, ${position.longitude}");
//gps.clear();
//gps.add(
// "-- lat : ${position.latitude}, lon : ${position.longitude} --");
//checkForCheckin(position.latitude, position.longitude);
print("--- call check checkin");
print("---- skip gps is ${skip_gps.toString()} ----");
//});
}
//print(position == null ? 'Unknown' : 'current position is ${position.latitude.toString()}, ${position.longitude.toString()}');
});
} catch (err) {
locationPermission.clear();
locationPermission.add(err.toString());
}
ever(indexController.connectionStatusName, connectionChanged);
}
void startGPSTimer() {
// If a timer is already running, we first cancel it
_GPStimer?.cancel();
// Start a new timer that fires every 3 seconds
_timer = Timer.periodic(Duration(seconds: 1), (timer) async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
current_lat = position.latitude;
current_lon = position.longitude;
if (is_gps_selected.value) {
double czoom = indexController.rogMapController.zoom;
indexController.rogMapController
.move(LatLng(position.latitude, position.longitude), czoom);
//checkForCheckin(position.latitude, position.longitude);
print("--- call check checkin");
print("---- skip gps is ${skip_gps.toString()} ----");
}
});
}
void stopGPSTimer() {
_GPStimer?.cancel();
}
Future<void> startGame() async {
await checkForCheckin();
}
@override
void onClose() {
positionStream?.cancel();
_GPStimer?.cancel();
super.onClose();
super.onClose();
}
@override
void onInit() async {
//initGPS();
startGPSTimer();
startGame();
super.onInit();
}
readUserToken() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
indexController.userToken = prefs.getString("user_token");
}
@override
void onReady() async {
await readUserToken();
final token = indexController.userToken;
if (token != null && token.isNotEmpty) {
await indexController.loadUserDetailsForToken(token);
fixMapBound(token);
return;
}
Get.toNamed(AppPages.LOGIN)!.then((value) {
if (indexController.currentUser.isNotEmpty) {
final tk = indexController.currentUser[0]["token"];
fixMapBound(tk);
} else {
Get.toNamed(AppPages.TRAVEL);
PerfectureService.getSubExt("9").then((value) {
if (value != null) {
LatLngBounds bnds = LatLngBounds(
LatLng(value[1], value[0]), LatLng(value[3], value[2]));
indexController.mapController
.fitBounds(bnds); //.centerZoomFitBounds(bnds);
}
});
}
});
super.onReady();
}
void fixMapBound(String token) {
//String _token = indexController.currentUser[0]["token"];
indexController.switchPage(AppPages.INITIAL);
LocationService.getLocationsExt(token).then((value) {
if (value != null) {
print("--- loc ext is - $value ----");
LatLngBounds bnds = LatLngBounds(
LatLng(value[1], value[0]), LatLng(value[3], value[2]));
print("--- bnds is - $bnds ----");
indexController.mapController.fitBounds(
bnds,
);
indexController.currentBound.clear();
indexController.currentBound.add(bnds);
indexController.loadLocationsBound();
}
});
}
void connectionChanged(String val) {
print('----- %%%%%%%%%%%%%%%%%%%%% ----- $val');
Map<String, dynamic> _res = {};
if (val == "wifi" || val == "mobile") {
String _token = indexController.currentUser[0]["token"];
DatabaseHelper db = DatabaseHelper.instance;
db.allRogianing().then((value) {
value.forEach((e) async {
if (e.rog_action_type == 0) {
_res = await ExternalService().StartRogaining();
} else if (e.rog_action_type == 1) {
var datetime = DateTime.fromMicrosecondsSinceEpoch(e.checkintime!);
_res = await ExternalService().makeCheckpoint(
e.user_id!,
_token,
getFormatedTime(datetime),
e.team_name!,
e.cp_number!,
e.event_code!,
e.image!);
} else if (e.rog_action_type == 2) {
var datetime = DateTime.fromMicrosecondsSinceEpoch(e.checkintime!);
_res = await ExternalService().makeGoal(
e.user_id!,
_token,
e.team_name!,
e.image!,
getFormatedTime(datetime),
e.event_code!);
}
if (_res.isNotEmpty) {
db.deleteRogaining(e.id!);
}
});
});
}
}
void checkPermission() async {
LocationPermission permission = await Geolocator.checkPermission();
if (permission != LocationPermission.whileInUse ||
permission != LocationPermission.always) {
locationPermission.clear();
locationPermission.add(permission.name);
permission = await Geolocator.requestPermission();
}
}
Destination? destinationById(int id) {
Destination? d;
print("--- target des - $id ----");
for (Destination ss in destinations) {
print("--- des - ${ss.location_id} ----");
if (ss.location_id == id) {
d = ss;
break;
}
}
return d;
}
void deleteDestination(Destination d) {
//int id = destinations[index].location_id!;
//print("---- index ${destinations[index].location_id!}-----");
for (Destination ss in destinations) {
if (ss.location_id == d.location_id) {
destinations.remove(ss);
break;
}
}
DatabaseHelper db = DatabaseHelper.instance;
db.deleteDestination(d.location_id!).then((value) {
PopulateDestinations();
});
}
void deleteDBDestinations() {
DatabaseHelper db = DatabaseHelper.instance;
db.deleteAllDestinations().then((value) {
PopulateDestinations();
});
}
// ---------- database ------------------///
void addDestinations(Destination dest) {
print(
'------ destination controller in add destination ${dest.checkin_radious} ---- :::::');
DatabaseHelper db = DatabaseHelper.instance;
db.getDestinationByLatLon(dest.lat!, dest.lon!).then((value) {
if (value.isNotEmpty) {
db.deleteDestination(value[0].location_id!).then((value) {
db.insertDestination(dest).then((value) {
print(
"----- destination controller deleted and inserted destination id $value ---- :::::");
PopulateDestinations();
});
});
} else {
db.insertDestination(dest).then((value) {
print("----- destination controller added as new $value--- :::::");
PopulateDestinations();
});
}
});
}
void toggleSelection(Destination dest) async {
DatabaseHelper db = DatabaseHelper.instance;
await db.toggleSelecttion(dest);
destinations.clear();
db.getDestinations().then((value) {
destinationCount.value = 0;
currentSelectedDestinations.clear();
for (Destination d in value) {
//print("------ destination controller populating destination-------- ${d.checkedin}-------- :::::");
//print("-----populated----- ${d.toMap()}");
if (d.selected!) {
currentSelectedDestinations.add(d);
}
destinations.add(d);
}
destinationCount.value = destinations.length;
});
}
buildShowDialog(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return const Center(
child: CircularProgressIndicator(),
);
});
}
void destinationMatrixFromCurrentPoint(List<Destination> points) {
buildShowDialog(Get.context!);
MatrixService.getDestinations(points).then((mat) {
print(" matrix is ------- $mat");
matrix = mat;
try {
indexController.routePoints = [];
indexController.routePointLenght.value = 0;
DestinationService.getDestinationLine(points, matrix)?.then((value) {
indexController.routePoints = value;
indexController.routePointLenght.value =
indexController.routePoints.length;
//Get.toNamed(AppPages.TRAVEL);
});
destinationCount.value = destinations.length;
} catch (_) {
skip_gps = false;
return;
} finally {
Get.back();
}
});
}
void PopulateDestinations() {
print(
"--------- destination controller populsting destinations ----------- ::::::");
DatabaseHelper db = DatabaseHelper.instance;
destinations.clear();
db.getDestinations().then((value) {
destinationCount.value = 0;
for (Destination d in value) {
print(
"------ destination controller populating destination-------- ${d.checkedin}-------- :::::");
print("-----populated----- ${d.toMap()}");
destinations.add(d);
}
// destinationCount.value = 0;
print(
"------ destination controller destinationcount-------- $destinationCount-------- :::::");
// MatrixService.getDestinations(value).then((mat){
// print(" matrix is ------- ${mat}");
// matrix = mat;
// try{
// getRoutePoints();
// destinationCount.value = destinations.length;
// }
// catch(_){
// skip_gps = false;
// return;
// }
// });
});
}
void makeOrder(Destination d, int dir) {
DatabaseHelper db = DatabaseHelper.instance;
db.updateOrder(d, dir).then((value) {
PopulateDestinations();
});
}
void makeNext(Destination pt) {
for (int i = 0; i <= destinations.length - 1; i++) {
Destination p = destinations[i];
if (p.lat == pt.lat && p.lon == pt.lon) {
if (indexController.currentDestinationFeature.isNotEmpty) {
indexController.currentDestinationFeature.clear();
}
if (i >= destinations.length - 1) {
indexController.currentDestinationFeature.add(destinations[0]);
//getAction();
} else {
indexController.currentDestinationFeature.add(destinations[i + 1]);
//getAction();
}
}
}
}
void makePrevious(Destination pt) {
for (int i = 0; i <= destinations.length - 1; i++) {
Destination p = destinations[i];
if (p.lat == pt.lat && p.lon == pt.lon) {
if (indexController.currentDestinationFeature.isNotEmpty) {
indexController.currentDestinationFeature.clear();
}
if (i <= 0) {
indexController.currentDestinationFeature
.add(destinations[destinations.length - 1]);
//getAction();
} else {
indexController.currentDestinationFeature.add(destinations[i - 1]);
//getAction();
}
}
}
}
}