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.
 
 

611 lines
20 KiB

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_svg/svg.dart';
import 'package:teso/Classes/API%20Clasess/CouponDetails.dart';
import 'package:teso/Classes/API%20Clasess/Product.dart';
import 'package:teso/Classes/API%20Clasess/TesoBusinessDetail.dart';
import 'package:camera/camera.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:page_transition/page_transition.dart' as Transition;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:teso/Pages/Personnal.dart';
import 'package:teso/Pages/Sub_Pages/Notifications/ChatScreen.dart';
import 'package:teso/Pages/Sub_Pages/PersonalSub/Settings.dart';
import 'package:teso/Pages/Sub_Pages/PopUp/Personalized.dart';
import 'package:teso/Pages/codeQR.dart';
import 'package:teso/Pages/notifications.dart';
import 'package:teso/providers/pageAnimations.dart';
import 'package:teso/teso_fab.dart';
import 'package:teso/util/SizeConfig.dart';
import 'package:teso/util/consts.dart';
import 'Classes/API Clasess/CouponHead.dart';
import 'Pages/Sub_Pages/Coupons/ProximityCoupons.dart';
import 'Pages/Sub_Pages/homeSub/MyCoupons.dart';
import 'Pages/explore.dart';
import 'package:teso/Pages/LandingPage.dart';
import 'package:http/http.dart' as http;
import 'package:firebase_auth/firebase_auth.dart';
import 'package:teso/Pages/scannerqr.dart';
import 'package:provider/provider.dart';
import 'package:teso/providers/user_provider.dart';
import 'package:teso/providers/device_provider.dart';
import 'package:teso/Notifications/NotificationPlugin.dart';
import 'package:teso/Classes/Payload.dart';
import 'dart:convert';
import 'package:teso/Pages/Sub_Pages/Coupons/ProximityCoupons.dart';
import 'package:teso/Pages/DesireComeTrue.dart';
import 'package:teso/Pages/Sub_Pages/PersonalSub/CompleteProfile.dart';
import 'package:teso/Classes/TesoUser.dart';
import 'package:teso/Pages/Sub_Pages/CoinPurchase.dart';
import 'package:teso/Classes/NotificationSpliter.dart';
import 'Pages/home.dart';
class MainScreens extends StatefulWidget {
final List<CameraDescription> connectedCameras;
const MainScreens({Key? key, required this.connectedCameras}) : super(key: key);
@override
_MainScreensState createState() => _MainScreensState();
}
class _MainScreensState extends State<MainScreens>
with TickerProviderStateMixin {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
int _page = 0;
PageController? _pageController;
String? result = "";
ScrollController _scrollBottomBarController = new ScrollController();
bool isScrollingDown = false;
double bottomBarHeight = 75;
final picker = ImagePicker();
late FirebaseAuth _auth;
String? dd;
bool _initialized = false;
bool navVisible = true;
Future _scanQRCode() async {
result = "";
result = await Navigator.push(
context,
PageTransition(
type: PageTransitionType.downToUp,
child: QRCodeScanner(),
),
);
try {
if (result!.isNotEmpty) {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.downToUp,
child: ScanQR(
shopID: result,
),
),
);
}
} catch (ex) {
setState(() {
result = "Unknown Error $ex";
});
}
}
@override
void dispose() {
super.dispose();
_pageController!.dispose();
_scrollBottomBarController.removeListener(() {});
DefaultCacheManager().emptyCache();
}
void clear() async {
await DefaultCacheManager().emptyCache();
}
@override
void initState() {
notificationPlugin
.setListenerForLowerVersions(onNotificationInLowerVersions);
notificationPlugin.setOnNotificationClick(onNotificationClick);
Provider.of<UserProvider>(context, listen: false)
.connectionToServer(context);
Provider.of<UserProvider>(context, listen: false).getCurrentUser();
Provider.of<UserProvider>(context, listen: false).getUserInformation();
Provider.of<DeviceProvider>(context, listen: false).checkBackgroundMode();
Provider.of<UserProvider>(context, listen: false).getMonthlyStatus();
Provider.of<UserProvider>(context, listen: false).loadFriends();
Provider.of<UserProvider>(context, listen: false).getCoupons();
Provider.of<UserProvider>(context, listen: false).checkBlockedUsers();
super.initState();
_pageController = PageController(initialPage: 0, keepPage: false);
SharedPreferences.getInstance().then((prefs) async {
String? deviceToken;
await _firebaseMessaging.getToken().then((token) {
deviceToken = token;
});
Map<String, dynamic> user =
jsonDecode(prefs.getString("currentUser")!) as Map<String, dynamic>;
TesoUser currentuser = TesoUser.fromJSON(user);
Map<String, dynamic> updates = {
'chattingWith': "",
'typing': false,
"username": currentuser.username,
"deviceToken": deviceToken
};
FirebaseFirestore.instance
.collection('users')
.doc(currentuser.userGUID)
.update(updates);
init(context);
if (currentuser.dateOfBirth == null || currentuser.gender == null) {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.leftToRight,
child: CompleteProfile(),
));
}
});
}
void navigationTapped(int page) {
if (page == 0) {
_pageController!.jumpToPage(0);
} else if (page == 1) {
_pageController!.jumpToPage(1);
} else if (page == 2) {
_scanQRCode();
} else if (page == 3) {
_pageController!.jumpToPage(2);
} else {
_pageController!.jumpToPage(3);
}
}
void onPageChanged(int page) {
setState(() {
if (page < 2) {
this._page = page;
} else {
this._page = page + 1;
}
});
}
void settingsDialog(context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
enableDrag: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(30.0)),
),
builder: (BuildContext bc) {
return Setting(
logOut: logOut,
connectedCameras: widget.connectedCameras,
);
});
}
void logOut() async {
try {
SharedPreferences.getInstance().then((prefs) async {
String token = prefs.getString('tokensTeso')!;
String? id = prefs.getString('id');
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': token
};
var register = Uri.parse(serverLocation + 'api/logout');
var client = await http.get(register, headers: requestHeaders);
if (client.statusCode == 200) {
clear();
FirebaseFirestore.instance
.collection('users')
.doc(id)
.update({'deviceToken': ""});
_auth = FirebaseAuth.instance;
await _auth.signOut();
await prefs.clear();
await prefs.setBool("launched", true);
// print(r.toString());
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => LandingPage()),
(Route<dynamic> route) => false);
} else {}
});
} catch (e) {
print(e);
}
}
bool onWillPop() {
_pageController!.previousPage(
duration: Duration(milliseconds: 200),
curve: Curves.linear,
);
return false;
}
Widget build(BuildContext context) {
return Scaffold(
extendBody: true,
body: WillPopScope(
onWillPop: () => Future.sync(onWillPop),
child: Stack(
children: [
PageView(
physics: NeverScrollableScrollPhysics(),
controller: _pageController,
onPageChanged: onPageChanged,
children: <Widget>[
Home(),
Explore(
connectedCameras: widget.connectedCameras,
),
MyCoupons(),
Personnal(showSettings: settingsDialog,),
],
),
Align(
alignment: Alignment.bottomCenter,
child: Consumer<UserProvider>(builder:
(BuildContext context, UserProvider user, Widget? child) {
if (user.saving)
return Container(
width: double.infinity,
height: 30,
alignment: Alignment.center,
padding: EdgeInsets.all(
SizeConfig.safeBlockVertical * 1.3,
),
margin: EdgeInsets.only(
// left: MediaQuery.of(context).size.width * 0.119,
// right: MediaQuery.of(context).size.width * 0.119,
bottom: SizeConfig.safeBlockVertical * 15,
),
color: Color.fromRGBO(0, 0, 0, 0.2),
child: Text("Saving...",
style: TextStyle(
color: Colors.white,
)),
);
else
return Container();
}),
),
],
),
),
floatingActionButton: TesoFAB(
distance: SizeConfig.safeBlockVertical * 17,
children: [
ActionButton(
onPressed: () => navigationTapped(0),
icon: const Icon(Icons.home),
),
ActionButton(
onPressed: () => navigationTapped(1),
icon: SvgPicture.asset(
"assets/images/search.svg",
color: Colors.black,
fit: BoxFit.contain,
width: SizeConfig.safeBlockVertical * 3.2,
),
),
ActionButton(
onPressed: () => navigationTapped(3),
icon: SvgPicture.asset(
"assets/images/coupon.svg",
color: Colors.black,
fit: BoxFit.contain,
width: SizeConfig.safeBlockVertical * 3.2,
),
),
ActionButton(
onPressed: () => navigationTapped(4),
icon: const Icon(Icons.person),
),
],
),
// bottomNavigationBar: bottomOptions(context),
);
}
onNotificationInLowerVersions(ReceivedNotification receivedNotification) {}
onNotificationClick(String payload) async {
Payload load = Payload.fromJSON(json.decode(payload.toString()));
switch (load.loadID) {
case "TESN001":
await Navigator.of(context).push(
Transition.PageTransition(
type: Transition.PageTransitionType.bottomToTop,
child: ProximityCoupons(),
),
);
break;
case "TESN002":
await Navigator.push(
context,
Transition.PageTransition(
child: DesireComeTrue(),
type: Transition.PageTransitionType.fade,
),
);
break;
case "TESN000":
navigationTapped(3);
break;
case "TESN0R0":
navigationTapped(3);
break;
case "TESN003":
await Navigator.push(
context,
Transition.PageTransition(
child: Coins(initalPage: 0),
type: Transition.PageTransitionType.fade,
),
);
break;
case "TESN004":
TesoUser user = new TesoUser();
user.firstname = load.load2;
user.userGUID = load.load1;
user.lastname = load.load3;
await Navigator.push(
context,
Transition.PageTransition(
child: ChatScreen(
user: user,
),
type: Transition.PageTransitionType.fade,
),
);
break;
}
}
void _fetchMessage(RemoteMessage? message, BuildContext context) async {
if (message == null || message.notification == null) return;
final Map<String, dynamic> _data = message.data;
final RemoteNotification notification = message.notification!;
Payload payload = await NotificationSplitter.getPayload(_data, context);
await notificationPlugin.showNotification(
notification.title,
notification.body,
payload.toString(),
);
if (payload.load2 != null && payload.load2 == "personalized") {
try {
var coup = jsonDecode(payload.load1!);
Product product = new Product();
product.productName = payload.load7;
product.unitPrice = double.parse(payload.load6!);
TesoBusinessDetail business = new TesoBusinessDetail();
business.businessName = payload.load5;
CouponsHead head = new CouponsHead();
head.businessId = coup["BusinessId"];
head.couponId = payload.load3;
head.expiration = DateTime.parse(coup["Expiration"].toString());
head.lower = coup["LowerLimit"];
head.quantity = 1;
head.state = payload.load4;
head.targetProduct = coup["TargetProduct"];
head.type = coup["Type"];
head.upper = coup["UpperLimit"];
head.generated = DateTime.parse(coup["Generated"].toString());
CouponDetails details = new CouponDetails();
details.businessId = head.businessId;
details.condition = payload.load4;
details.targetProduct = product;
details.issuer = business;
details.lowerLimit = head.lower;
details.upperLimit = head.upper;
await Navigator.push(
context,
PageTransition(
type: PageTransitionType.fade,
child: PersonalCoupon(
details: details,
head: head,
),
),
);
} catch (e) {
print(e);
}
}
}
Future<void> init(BuildContext context) async {
if (!_initialized) {
await _firebaseMessaging.requestPermission();
_firebaseMessaging
.getInitialMessage()
.then((message) => _fetchMessage(message, context));
FirebaseMessaging.onMessage
.listen((message) => _fetchForegroundMessage(message, context));
FirebaseMessaging.onMessageOpenedApp
.listen((message) => _fromBackground(message, context));
_firebaseMessaging.getToken().then((token) {
// print('token: $token');
});
_initialized = true;
}
}
void _fromBackground(RemoteMessage message, BuildContext context) async {
if (message.notification == null) return;
final Map<String, dynamic> _data = message.data;
Payload payload = await NotificationSplitter.getPayload(_data, context);
if (payload.load2 != null && payload.load2 == "personalized") {
try {
var coup = jsonDecode(payload.load1!);
Product product = new Product();
product.productName = payload.load7;
product.unitPrice = double.parse(payload.load6!);
TesoBusinessDetail business = new TesoBusinessDetail();
business.businessName = payload.load5;
CouponsHead head = new CouponsHead();
head.businessId = coup["BusinessId"];
head.couponId = payload.load3;
head.expiration = DateTime.parse(coup["Expiration"].toString());
head.lower = coup["LowerLimit"];
head.quantity = 1;
head.state = payload.load4;
head.targetProduct = coup["TargetProduct"];
head.type = coup["Type"];
head.upper = coup["UpperLimit"];
head.generated = DateTime.parse(coup["Generated"].toString());
CouponDetails details = new CouponDetails();
details.businessId = head.businessId;
details.condition = payload.load4;
details.targetProduct = product;
details.issuer = business;
details.lowerLimit = head.lower;
details.upperLimit = head.upper;
await Navigator.push(
context,
PageTransition(
type: PageTransitionType.fade,
child: PersonalCoupon(
details: details,
head: head,
),
),
);
} catch (e) {
print(e);
}
} else {
switch (_data["notificationType"]) {
case "chats":
TesoUser user = new TesoUser();
user.firstname = payload.load2;
user.userGUID = payload.load1;
user.lastname = payload.load3;
await Navigator.push(
context,
Transition.PageTransition(
child: ChatScreen(
user: user,
),
type: Transition.PageTransitionType.fade,
),
);
break;
default:
navigationTapped(3);
break;
}
}
}
void _fetchForegroundMessage(
RemoteMessage message, BuildContext context) async {
if (message.notification == null) return;
final Map<String, dynamic> _data = message.data;
final RemoteNotification notification = message.notification!;
Payload payload = await NotificationSplitter.getPayload(_data, context);
await notificationPlugin.showNotification(
notification.title,
notification.body,
payload.toString(),
);
if (payload.load2 != null && payload.load2 == "personalized") {
try {
var coup = jsonDecode(payload.load1!);
Product product = new Product();
product.productName = payload.load7;
product.unitPrice = double.parse(payload.load6!);
TesoBusinessDetail business = new TesoBusinessDetail();
business.businessName = payload.load5;
CouponsHead head = new CouponsHead();
head.businessId = coup["BusinessId"];
head.couponId = payload.load3;
head.expiration = DateTime.parse(coup["Expiration"].toString());
head.lower = coup["LowerLimit"];
head.quantity = 1;
head.state = payload.load4;
head.targetProduct = coup["TargetProduct"];
head.type = coup["Type"];
head.upper = coup["UpperLimit"];
head.generated = DateTime.parse(coup["Generated"].toString());
CouponDetails details = new CouponDetails();
details.businessId = head.businessId;
details.condition = payload.load4;
details.targetProduct = product;
details.issuer = business;
details.lowerLimit = head.lower;
details.upperLimit = head.upper;
await Navigator.push(
context,
PageTransition(
type: PageTransitionType.fade,
child: PersonalCoupon(
details: details,
head: head,
),
),
);
} catch (e) {
print(e);
}
} else if (payload.loadID == "TESN0R0") {
SharedPreferences.getInstance().then((prefs) async {
String currentSaveUser = prefs.getString("currentUser")!;
Map<String, dynamic> olduser =
jsonDecode(currentSaveUser) as Map<String, dynamic>;
TesoUser user = TesoUser.fromJSON(olduser);
user.gold =
(int.parse(user.gold!) + int.parse(_data["reward"])).toString();
Provider.of<UserProvider>(context, listen: false).setUser(user);
});
}
}
Widget bottomOptions(context) {
return BottomNavigationBar(
//iconSize: 19.5,
showSelectedLabels: false,
showUnselectedLabels: false,
backgroundColor: Theme.of(context).primaryColor,
selectedItemColor: Theme.of(context).colorScheme.secondary,
unselectedItemColor: Colors.grey[500],
elevation: 150,
type: BottomNavigationBarType.fixed,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
Icons.home,
size: SizeConfig.safeBlockHorizontal * 6.7,
),
label: "Home",
tooltip: ""),
BottomNavigationBarItem(
icon: Icon(
Icons.search,
size: SizeConfig.safeBlockHorizontal * 6.7,
),
label: ("Explore"),
),
],
onTap: navigationTapped,
// currentIndex: _page,
);
}
}