import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:geojson/geojson.dart'; import 'package:geolocator/geolocator.dart'; import 'package:get/get.dart'; import 'package:latlong2/latlong.dart'; import 'package:rogapp/model/destination.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/maxtrix_service.dart'; import 'package:rogapp/services/reacking_service.dart'; import 'package:rogapp/utils/database_helper.dart'; import 'dart:async'; import 'package:rogapp/widgets/bottom_sheet_widget.dart'; class DestinationController extends GetxController { late LocationSettings locationSettings; var destinationCount = 0.obs; List destinations = [].obs; List> destination_index_data = >[].obs; List currentSelectedDestinations = [].obs; bool checking_in = false; List isSelected = [true].obs; BuildContext? context; List gps = ["-- stating --"].obs; List locationPermission = [" -- starting -- "].obs; Map matrix = {}; final IndexController indexController = Get.find(); Future getDEstinationForLatLong(double lat, double long)async { String jjjj = '{"id":1,"type":"Feature","geometry":{"type":"MultiPoint","coordinates":[[136.731357,35.370094]]},"properties":{"location_id":915101,"location_name":"柳津","category":"買い物","zip":"〒501-6100","address":"柳津町字仙右城7696-1"}}'; for(final d in destinations){ // var geom = d["location"]["geometry"]; // var props = d["location"]["properties"]; // print("--props- ${d["location"]["geometry"]["coordinates"][0][1]}"); // List geom_multi = [geom]; // Map final_geom = {"features":[{"id":d["id"],"type":"Feature", "geometry": geom, "properties": props}]}; // //print("----- geom : ${final_geom}"); // String js = json.encode(final_geom); // //print("---features-- ${js}-----"); // GeoJsonFeatureCollection features = await featuresFromGeoJson(js); // GeoJsonMultiPoint p = features.collection[0].geometry as GeoJsonMultiPoint; if(lat == d.lat && long == d.lon){ return d; } } } checkForCheckin(double la, double ln){ for(final d in destinations){ if(!checking_in) { checking_in = true; double lat = d.lat!; double lon = d.lon!; LatLng p = LatLng(lat, lon); getDEstinationForLatLong(lat, lon).then((value){ var distance = Distance(); double dist = distance.as(LengthUnit.Meter, LatLng(lat, lon), LatLng(la, ln)); double rad = value!.checkin_radious ?? double.infinity; bool auto_checkin = value.auto_checkin == 0 ? false : true; indexController.currentDestinationFeature.add(value); //indexController.getAction(); if(rad >= dist){ if(auto_checkin){ makeCheckin(value, true); } else{ showModalBottomSheet(context: Get.context!, isScrollControlled: true, builder:((context) => BottomSheetWidget()) ).whenComplete((){ checking_in = false; }); } } // if(!checking_in){ // checking_in = true; // if(rad >= dist){ // if(auto_checkin){ // if(indexController.currentAction.isNotEmpty){ // print(indexController.currentAction[0]); // indexController.currentAction[0][0]["checkin"] = true; // Map temp = Map.from(indexController.currentAction[0][0]); // indexController.currentAction.clear(); // print("---temp---${temp}"); // indexController.currentAction.add([temp]); // } // indexController.makeAction(Get.context!); // } // else{ // showModalBottomSheet(context: Get.context!, isScrollControlled: true, // builder:((context) => BottomSheetWidget()) // ).whenComplete((){ // checking_in = false; // }); // } // } // } }); } } } void makeCheckin(Destination destination, bool action) async { print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ressssss ${action}@@@@@@@@@@@"); DatabaseHelper db = DatabaseHelper.instance; int res = await db.updateAction(destination, action); List ddd = await db.getDestinationByLatLon(destination.lat!, destination.lon!); print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ddddd ${ddd[0].checkedin} @@@@@@@@@@@"); print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ressssss ${res}@@@@@@@@@@@"); PopulateDestinations(); print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ after populating ${res} @@@@@@@@@@@"); print("---- database update resulr ------ res : ${res}-------"); } @override void onInit() async { super.onInit(); checkPermission(); PopulateDestinations(); print("------ in iniit"); if (defaultTargetPlatform == TargetPlatform.android) { locationSettings = AndroidSettings( accuracy: LocationAccuracy.bestForNavigation, distanceFilter: 00, forceLocationManager: true, intervalDuration: const Duration(seconds: 1), //(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.bestForNavigation, activityType: ActivityType.fitness, distanceFilter: 1, pauseLocationUpdatesAutomatically: false, // Only set to true if our app will be started up in the background. showBackgroundLocationIndicator: true ); } else { locationSettings = LocationSettings( accuracy: LocationAccuracy.high, distanceFilter: 30, ); } try { StreamSubscription positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen( (Position? position) { if(isSelected[0]){ 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(position == null ? 'Unknown' : 'current position is ${position.latitude.toString()}, ${position.longitude.toString()}'); }); } catch (err){ locationPermission.clear(); locationPermission.add(err.toString()); } } 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(); } } void deleteDestination(Destination d){ //int id = destinations[index].location_id!; //print("---- index ${destinations[index].location_id!}-----"); for(Destination ss in currentSelectedDestinations){ if(ss.location_id == d.location_id){ currentSelectedDestinations.remove(ss); break; } } DatabaseHelper db = DatabaseHelper.instance; db.deleteDestination(d.location_id!).then((value){ PopulateDestinations(); }); // DestinationService.deleteDestination(id).then((val){ // destination_index_data.clear(); // PopulateDestinations(); // print("####### dest id : ${id}"); // }); } // ---------- database ------------------/// void addDestinations(Destination dest){ print('------ destination controller in add destination ${dest.name} ---- :::::'); 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 PopulateDestinations(){ print("--------- destination controller populsting destinations ----------- ::::::"); destinations.clear(); destinationCount.value = 0; DatabaseHelper db = DatabaseHelper.instance; db.getDestinations().then((value){ for(Destination d in value){ for(Destination s in currentSelectedDestinations){ if(d.location_id == s.location_id){ d.selected = !d.selected!; } } destinations.add(d); } // destinationCount.value = 0; destinationCount.value = destinations.length; print("------ destination controller destinationcount-------- ${destinationCount}-------- :::::"); MatrixService.getDestinations(value).then((mat){ print(mat); matrix = mat; }); }); // if(indexController.currentUser.isNotEmpty){ // int user_id = indexController.currentUser[0]["user"]["id"]; // print(user_id); // DestinationService.getDestinations(user_id).then((value){ // destinations.clear(); // destinations = value; // destinationCount.value = 0; // destinationCount.value = destinations.length; // MatrixService.getDestinations(value).then((mat){ // print(mat); // matrix = mat; // }); // //var val = value[2]["location"]["id"]; // //print("-----current destinations ----- ${val}"); // }); // } // else{ // Get.toNamed(AppPages.LOGIN); // } } void makeOrder(int action_id, int order, String dir){ DestinationService.updateOrder(action_id, order, dir).then((value){ //print("----action value----${value}"); PopulateDestinations(); destination_index_data.clear(); }); } 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(GeoJsonFeature fs){ // if(rog_mode == 1){ // DestinationController destinationController = Get.find(); // print("---- destination index--- ${destinationController.destination_index_data} --------"); // } // else { // GeoJsonFeature pt = fs as GeoJsonFeature; // for(int i=0; i<= locations[0].collection.length - 1; i++){ // GeoJsonMultiPoint p = locations[0].collection[i].geometry as GeoJsonMultiPoint; // if(p.geoSerie!.geoPoints[0].latitude == pt.geometry!.geoSerie!.geoPoints[0].latitude && p.geoSerie!.geoPoints[0].longitude == pt.geometry!.geoSerie!.geoPoints[0].longitude ){ // if(currentFeature.length > 0){ // currentFeature.clear(); // } // if(i == 0 ){ // currentFeature.add(locations[0].collection[locations[0].collection.length -1] as GeoJsonFeature); // getAction(); // } // else{ // currentFeature.add(locations[0].collection[i - 1] as GeoJsonFeature); // getAction(); // } // } // } // } // } }