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.
 
 

470 lines
15 KiB

import 'dart:convert';
import 'package:connectivity/connectivity.dart';
import 'package:teso/Classes/Connection.dart';
import 'package:teso/Classes/Firebase/Posts.dart';
import 'package:teso/Pages/Sub_Pages/@Generic/SuccessRedeem.dart';
import 'package:teso/Pages/Sub_Pages/@Generic/ErrorRedeem.dart';
import 'package:teso/Classes/API%20Clasess/CouponDetails.dart';
import 'package:teso/providers/pageAnimations.dart';
import 'package:teso/util/consts.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:teso/Classes/TesoUser.dart';
import 'package:teso/Classes/API Clasess/UserFavCategory.dart';
import 'package:teso/Classes/API Clasess/CouponHead.dart';
import 'package:teso/Notifications/NotificationPlugin.dart';
import 'package:teso/Classes/Payload.dart';
class UserProvider extends ChangeNotifier {
UserProvider() {
getCurrentUser();
}
TesoUser? currentUser;
List<String?>? interest = <String>[];
List<FBPosts> posts = <FBPosts>[];
List<TesoUser> friends = <TesoUser>[];
List<CouponDetails> mycoupons = <CouponDetails>[];
bool wifi = false;
bool firstTime = true;
bool saving = false;
List<String> blockedContent = <String>[];
List<String?> blockedUsers = <String?>[];
List<TesoUser> blockUserList = <TesoUser>[];
void updateUser(user) async {
currentUser = await update(user);
SharedPreferences.getInstance().then((prefs) {
prefs.setString("currentUser", currentUser.toString());
});
notifyListeners();
}
void setUser(user) {
currentUser = user;
SharedPreferences.getInstance().then((prefs) {
prefs.setString("currentUser", currentUser.toString());
});
notifyListeners();
}
getCurrentUser() async {
String? currentSaveUser;
SharedPreferences.getInstance().then((prefs) async {
currentSaveUser = prefs.getString("currentUser");
if (currentSaveUser == null) {
} else {
Map<String, dynamic> user =
jsonDecode(currentSaveUser!) as Map<String, dynamic>;
TesoUser olduser = TesoUser.fromJSON(user);
currentUser = olduser;
prefs.setString("currentUser", currentUser.toString());
}
});
Future.delayed(Duration(seconds: 5), () => notifyListeners());
return currentUser;
}
setFavs(List<String?> categories) {
interest = categories;
SharedPreferences.getInstance().then((prefs) {
prefs.setStringList("favoriteCats", categories as List<String>);
});
notifyListeners();
}
getFavs() async {
try {
await pullFavoriteCategories();
} catch (e) {
SharedPreferences.getInstance().then((prefs) {
interest = prefs.getStringList("favoriteCats");
if (interest != null) if (interest!.isEmpty) {
interest = <String>[];
}
});
}
}
Future<TesoUser?> update(TesoUser? user) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')!
};
var register2 = serverLocation + 'users/updateUser';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(user), headers: requestHeaders);
if (client1.statusCode == 200) {
Map handler = jsonDecode(client1.body);
TesoUser tokenHandler = TesoUser.fromJSON(handler as Map<String, dynamic>);
return tokenHandler;
} else {
return null;
}
}
Future<List<String?>?> pullFavoriteCategories() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<UserFavCategory> favs;
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')!
};
var register2 = serverLocation + 'favoriteCategories/pullUser';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(prefs.getString("id")), headers: requestHeaders);
if (client1.statusCode == 200) {
var handler = jsonDecode(client1.body);
favs = List<UserFavCategory>.from(
handler.map((model) => UserFavCategory.fromJSON(model)).toList());
setFavs(favs.map((e) => e.categoryCode).toList());
return interest = favs.map((e) => e.categoryCode).toList();
} else {
return null;
}
}
updateFavoriteCategories(List<String> catF) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? id = prefs.getString("id");
List<UserFavCategory> favs = <UserFavCategory>[];
catF.forEach((element) async {
UserFavCategory category = new UserFavCategory();
category.userGuid = id;
category.categoryCode = element;
category.countID = DateTime.now().toString() + id!;
favs.add(category);
});
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')!
};
var register2 = serverLocation + 'favoriteCategories/updateFavorites';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(favs), headers: requestHeaders);
if (client1.statusCode == 200) {
setFavs(catF);
} else {
return null;
}
}
Future<void> getMonthlyStatus() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')!
};
try {
var register2 = serverLocation + 'monthly-desires/check-status';
var client1 =
await http.get(Uri.parse(register2), headers: requestHeaders);
if (client1.statusCode == 200) {
if (client1.body == "not submitted") {
Payload payload = new Payload();
payload.loadID = "TESN002";
payload.load1 = "DesireComeTrue";
await notificationPlugin.showNotification(
"Desire Come True",
"You haven't set up your Desire Come True list for next month",
payload.toString(),
);
}
}
} catch (e) {
print(e);
}
}
// coupons
Future<int> viewCoupon(CouponsHead coupon) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')!
};
try {
var register2 = serverLocation + 'coupons/viewCoupon';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(coupon), headers: requestHeaders);
if (client1.statusCode == 200) {
return 200;
} else {
return 400;
}
} catch (e) {
return 400;
}
}
Future<void> loadFriends() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("tokensTeso")!;
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': token
};
var register = serverLocation + 'relationships/friends';
var client = await http.get(Uri.parse(register), headers: requestHeaders);
if (client.statusCode == 200) {
var people = jsonDecode(client.body);
friends = List<TesoUser>.from(
people.map((model) => TesoUser.fromJSON(model)).toList());
notifyListeners();
}
}
Future<void> getUserInformation() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("tokensTeso")!;
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': token
};
var register = serverLocation + 'user_details/pullInformation';
var client = await http.get(Uri.parse(register), headers: requestHeaders);
if (client.statusCode == 200) {
var people = jsonDecode(client.body);
TesoUser user = TesoUser.fromJSON(people);
setUser(user);
}
}
Future<void> getCoupons() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("tokensTeso")!;
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': token
};
var register = serverLocation + 'coupons/acquiredcoupons';
var client = await http.get(Uri.parse(register), headers: requestHeaders);
if (client.statusCode == 200) {
var details = jsonDecode(client.body);
mycoupons = List<CouponDetails>.from(
details.map((model) => CouponDetails.fromJSON(model)).toList());
notifyListeners();
}
}
Future<void> redeemCoupon(CouponDetails coupon, context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': prefs.getString('tokensTeso')!
};
try {
var register2 = serverLocation + 'coupons/redeemCoupon';
var client1 = await http.post(Uri.parse(register2),
body: json.encode(coupon), headers: requestHeaders);
print(client1.body);
if (client1.statusCode == 200) {
var data = client1.body;
int? coins = int.tryParse(data);
Payload payload = new Payload();
payload.loadID = "TESN003";
payload.load1 = "CouponRedemption";
await notificationPlugin.showNotification(
"Coupon Redeem",
"You have successfully redeem a " +
coupon.issuer!.businessName! +
" " +
coupon.type! +
" coupon",
payload.toString(),
);
getCoupons();
await Navigator.pushReplacement(
context,
PageTransition(
child: SuccessfullyRedeemed(
couponDetails: coupon,
returns: coins,
),
type: PageTransitionType.fade,
),
);
Navigator.pop(context);
} else {
Navigator.pushReplacement(
context,
PageTransition(
child: ErrorRedeem(),
type: PageTransitionType.fade,
),
);
}
} catch (e) {
print(e);
Navigator.pushReplacement(
context,
PageTransition(
child: ErrorRedeem(),
type: PageTransitionType.fade,
),
);
}
}
connectionToServer(context) {
MyConnectivity _connectivity = MyConnectivity.instance;
_connectivity.initialise();
_connectivity.myStream.listen((source) {
if (source.keys.toList()[0] == ConnectivityResult.wifi &&
source.values.toList()[0]) {
final snackBar = SnackBar(
content: Text(
'Connected',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
backgroundColor: Colors.green,
duration: Duration(
seconds: 3,
),
);
if (!firstTime) ScaffoldMessenger.of(context).showSnackBar(snackBar);
firstTime = false;
wifi = true;
notifyListeners();
} else if (source.keys.toList()[0] == ConnectivityResult.mobile &&
source.values.toList()[0]) {
final snackBar = SnackBar(
content: Text(
'Connected',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
backgroundColor: Colors.green,
duration: Duration(
seconds: 3,
),
);
if (!firstTime) ScaffoldMessenger.of(context).showSnackBar(snackBar);
firstTime = false;
wifi = false;
notifyListeners();
} else {
final snackBar = SnackBar(
content: Text(
'No Internet Connection Available',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
action: SnackBarAction(
label: 'Retry',
textColor: Colors.white,
onPressed: () => connectionToServer(context),
),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
backgroundColor: Colors.red,
duration: Duration(
seconds: 3,
),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
firstTime = false;
wifi = false;
notifyListeners();
}
});
}
checkRelationship(String id) {
return friends.any((element) => element.userGUID == id);
}
checkBlockedUsers() async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("tokensTeso")!;
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': token
};
var register = serverLocation + 'users/blocked-users';
var client = await http.get(Uri.parse(register), headers: requestHeaders);
if (client.statusCode == 200) {
var people = jsonDecode(client.body);
blockUserList = List<TesoUser>.from(
people.map((model) => TesoUser.fromJSON(model)).toList());
blockedUsers = blockUserList.map((b) => b.userGUID).toList();
}
notifyListeners();
} catch (e) {
print(e);
}
}
checkBlockedContent() async {}
Future<void> blockUser(TesoUser user) async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("tokensTeso")!;
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': token
};
var register = serverLocation + 'relationships/block';
var client = await http.post(Uri.parse(register),
body: json.encode(user.userGUID), headers: requestHeaders);
if (client.statusCode == 200) {
blockedUsers.add(user.userGUID);
blockUserList.add(user);
notifyListeners();
}
} catch (_) {}
}
Future<void> unblockUser(TesoUser user) async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("tokensTeso")!;
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': token
};
var register = serverLocation + 'relationships/unblock';
var client = await http.post(Uri.parse(register),
body: json.encode(user.userGUID), headers: requestHeaders);
if (client.statusCode == 200) {
blockedUsers.remove(user.userGUID);
blockUserList.remove(user);
notifyListeners();
}
} catch (_) {}
}
}