You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

300 lines
9.4 KiB

import 'package:provider/provider.dart';
import 'package:teso/Classes/API%20Clasess/PostionAP.dart';
import 'package:teso/Classes/TesoUser.dart';
import 'package:teso/Pages/Sub_Pages/@Generic/prominentDisclosureBackground.dart';
import 'package:teso/providers/pageAnimations.dart';
import 'package:teso/providers/user_provider.dart';
import 'package:teso/util/consts.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:teso/Classes/API Clasess/ProximityCoupon.dart';
import 'package:teso/Classes/API Clasess/CouponHead.dart';
import 'package:geolocator/geolocator.dart';
import 'package:teso/Notifications/NotificationPlugin.dart';
import 'package:teso/Classes/Payload.dart';
import 'package:teso/Pages/Sub_Pages/@Generic/Error.dart';
class DeviceProvider extends ChangeNotifier {
bool serviceEnabled;
Location location = new Location();
bool _serviceEnabled;
LocationData _location;
StreamSubscription<LocationData> _locationSubscription;
List<ProximityCoupon> proximityCoupons = <ProximityCoupon>[];
bool fetching = false;
bool declining = false;
bool runFirst = true;
Position1 position = new Position1();
DeviceProvider() {
try {
checkBackgroundMode();
} catch (e) {
print(e);
}
}
void checkBackgroundMode() async {
final bool result = await location.isBackgroundModeEnabled();
serviceEnabled = result;
SharedPreferences.getInstance().then((prefs) {
serviceEnabled = prefs.getBool("backgroundService");
if (serviceEnabled == null) {
serviceEnabled = false;
} else {
serviceEnabled = prefs.getBool("backgroundService");
}
if (serviceEnabled) _listenLocation();
});
}
void toggleBackgroundMode(context) async {
try {
bool prominentResult = false;
if (!serviceEnabled) {
prominentResult = await Navigator.push(
context,
PageTransition(
child: ProminentDisclosure(),
type: PageTransitionType.leftToRight));
}
final bool result = await location.enableBackgroundMode(
enable: prominentResult,
);
serviceEnabled = result;
SharedPreferences.getInstance().then((prefs) {
prefs.setBool("backgroundService", serviceEnabled);
});
if (serviceEnabled) {
PermissionStatus status = await _requestPermission();
if (status == PermissionStatus.granted) {
await _requestService();
_listenLocation();
}
} else {
await _stopListen();
}
} on PlatformException catch (err) {
Navigator.push(
context,
PageTransition(
child: ErrorPage(error: err.message),
type: PageTransitionType.fade,
),
);
} catch (e) {
print(e);
Navigator.push(
context,
PageTransition(
child: ErrorPage(error: e.toString()),
type: PageTransitionType.fade,
),
);
}
notifyListeners();
}
Future<void> _requestService() async {
if (_serviceEnabled == null || !_serviceEnabled) {
final bool serviceRequestedResult = await location.requestService();
_serviceEnabled = serviceRequestedResult;
if (!serviceRequestedResult) {
return;
}
}
}
Future<void> _listenLocation() async {
_locationSubscription =
location.onLocationChanged.handleError((dynamic err) {
print(err.code);
_locationSubscription.cancel();
}).listen((LocationData currentLocation) async {
try {
double distanceInMeters = Geolocator.distanceBetween(
currentLocation.latitude,
currentLocation.longitude,
_location.latitude,
_location.longitude);
if (distanceInMeters >= 804.672 || runFirst) {
if (!fetching && !declining) {
position.latitude = currentLocation.latitude;
position.longitude = currentLocation.longitude;
await proxiCoupons();
if (proximityCoupons.length > 0) {
Payload payload = new Payload();
payload.loadID = "TESN001";
payload.load1 = "proximityCoupons";
await notificationPlugin.showNotification(
"Proximity Coupons",
"There are proximity coupons available in your area, click here to accept",
payload.toString(),
);
}
runFirst = false;
}
_location = currentLocation;
}
fetching = false;
} catch (e) {
if (!fetching && !declining) {
position.latitude = currentLocation.latitude;
position.longitude = currentLocation.longitude;
await proxiCoupons();
}
_location = currentLocation;
fetching = false;
}
});
}
Future<void> _stopListen() async {
try {
_locationSubscription.cancel();
} catch (e) {}
}
PermissionStatus _permissionGranted;
Future<PermissionStatus> _requestPermission() async {
if (_permissionGranted != PermissionStatus.granted) {
_permissionGranted = await location.requestPermission();
}
return _permissionGranted;
}
Future<List<ProximityCoupon>> proxiCoupons() async {
fetching = true;
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')
};
var register2 = serverLocation + 'coupons/proximity';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(position), headers: requestHeaders);
if (client1.statusCode == 200) {
var details = jsonDecode(client1.body);
proximityCoupons = List<ProximityCoupon>.from(
details.map((model) => ProximityCoupon.fromJSON(model)).toList());
notifyListeners();
return proximityCoupons;
} else {
return null;
}
}
Future<int> declineCoupon(CouponsHead couponsHead) async {
declining = true;
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')
};
var register2 = serverLocation + 'coupons/declineCoupon';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(couponsHead), headers: requestHeaders);
if (client1.statusCode == 200) {
declining = false;
return 1;
} else {
declining = false;
return 0;
}
}
Future<int> acceptCoupon(CouponsHead couponsHead, int cost, context) async {
try {
declining = true;
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')
};
TesoUser currentUser =
Provider.of<UserProvider>(context, listen: false).currentUser;
int remaining = int.parse(currentUser.silver) - cost.round();
if (remaining < 0) {
Payload payload = new Payload();
payload.loadID = "TESN003";
payload.load1 = "CouponAcquisition";
await notificationPlugin.showNotification(
"Insufficient coins",
"Unable to acquire coupon due to insufficient silver coins, get more silver coins to acquire coupons!!",
payload.toString(),
);
return 0;
}
// Calculations end
var register2 = serverLocation + 'coupons/acceptCoupon';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(couponsHead), headers: requestHeaders);
if (client1.statusCode == 200) {
currentUser.silver = remaining.toString();
Provider.of<UserProvider>(context, listen: false).setUser(currentUser);
declining = false;
Payload payload = new Payload();
payload.loadID = "TESN003";
payload.load1 = "CouponAcquisition";
await notificationPlugin.showNotification(
"Coupon Acquired",
client1.body.toString(),
payload.toString(),
);
Provider.of<UserProvider>(context, listen: false).getCoupons();
return 200;
} else if (client1.statusCode == 999) {
Payload payload = new Payload();
payload.loadID = "TESN003";
payload.load1 = "CouponAcquisition";
await notificationPlugin.showNotification(
"Unable to acquire coupon",
"Copies of coupon not available at the moment for acquisition, please try again after some time",
payload.toString(),
);
declining = false;
return client1.statusCode;
} else {
Payload payload = new Payload();
payload.loadID = "TESN003";
payload.load1 = "CouponAcquisition";
await notificationPlugin.showNotification(
"Unable to acquire coupon",
"An error occurred while trying to acquired coupon, please try again",
payload.toString(),
);
declining = false;
return client1.statusCode;
}
} catch (e) {
return 10;
}
}
}