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.
 
 

905 lines
30 KiB

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:location/location.dart';
import 'package:teso/Classes/API%20Clasess/Campaign.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:teso/Classes/Uploading.dart';
import 'package:teso/Pages/Campaigns.dart';
import 'package:camera/camera.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.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/PageWidgets/Uploads/Pending.dart';
import 'package:teso/Pages/Personnal.dart';
import 'package:teso/Pages/BusinessLocator.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/util/SizeConfig.dart';
import 'package:teso/util/consts.dart';
import 'Classes/API Clasess/CouponHead.dart';
import 'Pages/Sub_Pages/@Generic/Camera/Video/RecordVideo.dart';
import 'Pages/Sub_Pages/@Generic/prominentDisclosure.dart';
import 'Pages/Sub_Pages/Campaign/AuditionPage.dart';
import 'Pages/Sub_Pages/Coupons/ProximityCoupons.dart';
import 'Pages/explore.dart';
import 'Pages/home.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';
class MainScreens extends StatefulWidget {
final List<CameraDescription> connectedCameras;
const MainScreens({Key key, 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();
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).pullAds();
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 toogleNav(bool visibility) {
setState(() {
navVisible = visibility;
});
}
void navigationTapped(int page) {
if (page == 0) {
_pageController.jumpToPage(0);
} else if (page == 1) {
_pageController.jumpToPage(1);
} else if (page == 2) {
tesoDialog(context);
} 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 uploadsDialog(BuildContext context) {
showModalBottomSheet(
context: context,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(30.0)),
),
builder: (BuildContext bc) {
return Container(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: new Wrap(
children: <Widget>[
new Container(
width: double.infinity,
margin: EdgeInsets.only(
top: 15.0,
bottom: 5.0,
),
child: Center(
child: Text(
"Uploading....",
style: TextStyle(
fontSize: 20.0,
),
),
)),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Divider(),
),
getTiles(context),
new Container(
margin: EdgeInsets.symmetric(
vertical: 15.0,
),
child: new Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Theme.of(context).colorScheme.secondary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(25.0),
),
),
),
onPressed: () => Navigator.pop(context),
child: Text("Close"),
),
),
)
],
),
),
);
},
);
}
Widget getTiles(BuildContext context) {
try {
return Consumer<UserProvider>(
builder: (BuildContext context, UserProvider value, Widget child) {
List<Uploading> provider = value.getPending();
if (value.pending != null) {
return Column(
children: provider
.map<Widget>((item) => uploadTile(context, item))
.toList());
} else {
return Container();
}
});
} catch (e) {
return Container();
}
}
void tesoDialog(context) {
showModalBottomSheet(
context: context,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(30.0)),
),
builder: (BuildContext bc) {
return Container(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: new Wrap(
children: <Widget>[
new Container(
width: double.infinity,
margin: EdgeInsets.only(
top: 15.0,
bottom: 5.0,
),
child: Center(
child: Text(
"Tɛso",
style: TextStyle(
fontSize: 20.0,
),
),
)),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Divider(),
),
new ListTile(
leading: new Icon(
Icons.qr_code_sharp,
),
title: new Text('Scan QR Code'),
onTap: () => {_scanQRCode()},
),
// new ListTile(
// leading: new Icon(Ionicons.md_locate),
// title: new Text('Proximity Coupons'),
// onTap: () => {
// Navigator.push(
// context,
// Transition.PageTransition(
// type: Transition.PageTransitionType.bottomToTop,
// child: ProximityCoupons(),
// ),
// )
// },
// ),
new ListTile(
leading: new Icon(Icons.video_camera_back),
title: new Text('Post Video'),
onTap: () async {
await Navigator.of(context).push(
PageRouteBuilder(
opaque: true,
pageBuilder: (_, __, ___) => RecordVideo()),
);
},
),
new ListTile(
leading: new Icon(Icons.notifications),
title: new Text('Join Campaign'),
onTap: () => Navigator.push(
context,
Transition.PageTransition(
type: Transition.PageTransitionType.fade,
child: Campaigns(),
),
),
),
new ListTile(
leading: new Icon(Icons.location_on),
title: new Text('Business Locator'),
onTap: () async {
PermissionStatus alreadyConsent =
await Location.instance.hasPermission();
if (alreadyConsent != PermissionStatus.granted) {
bool results = await Navigator.push(
context,
PageTransition(
child: ProminentDisclosure(),
type: PageTransitionType.leftToRight));
if (results) {
await Location.instance.requestPermission();
Navigator.push(
context,
Transition.PageTransition(
type: Transition.PageTransitionType.leftToRight,
child: BusinessLocator(),
),
);
}
} else {
Navigator.push(
context,
Transition.PageTransition(
type: Transition.PageTransitionType.leftToRight,
child: BusinessLocator(),
),
);
}
},
),
new Container(
margin: EdgeInsets.symmetric(
vertical: 15.0,
),
child: new Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Theme.of(context).colorScheme.secondary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(25.0),
),
),
),
onPressed: () => Navigator.pop(context),
child: Text("Close"),
),
),
)
],
),
),
);
},
);
}
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(
showUploads: uploadsDialog,
toggle: toogleNav,
),
// VideoList(),
Explore(
connectedCameras: widget.connectedCameras,
),
Notifications(),
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();
}),
),
],
),
),
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;
case "TESN005":
Campaign campaignItem = Campaign(
businessID: load.load1,
campaignID: load.load2,
description: load.load3,
rewards: int.parse(load.load7),
startDate: DateTime.parse(load.load8),
status: load.load4,
targetProduct: load.load5,
title: load.load6);
await Navigator.push(
context,
PageTransition(
child: Audition(
campaign: campaignItem,
),
type: PageTransitionType.rightToLeft,
),
);
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 == null || 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;
case "campaign":
Campaign campaignItem = Campaign(
businessID: payload.load1,
campaignID: payload.load2,
description: payload.load3,
rewards: int.parse(payload.load7),
startDate: DateTime.parse(payload.load8),
status: payload.load4,
targetProduct: payload.load5,
title: payload.load6);
await Navigator.push(
context,
PageTransition(
child: Audition(
campaign: campaignItem,
),
type: PageTransitionType.rightToLeft,
),
);
break;
default:
navigationTapped(3);
break;
}
}
}
void _fetchForegroundMessage(
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);
}
} 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 AnimatedOpacity(
opacity: navVisible ? 1 : 0,
duration: Duration(seconds: 2),
child: Container(
height: SizeConfig.safeBlockVertical * 12,
margin: EdgeInsets.only(
bottom: SizeConfig.safeBlockVertical * 2,
left: MediaQuery.of(context).size.width * 0.05,
right: MediaQuery.of(context).size.width * 0.05,
),
padding: EdgeInsets.all(SizeConfig.safeBlockVertical * 0.54),
decoration: BoxDecoration(
color: Colors.white38,
borderRadius: BorderRadius.only(
topRight: Radius.circular(30),
topLeft: Radius.circular(30),
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30),
),
),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30.0),
topRight: Radius.circular(30.0),
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30),
),
child: 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"),
),
BottomNavigationBarItem(
icon: GestureDetector(
onLongPress: () => {_scanQRCode()},
child: ImageIcon(
AssetImage("assets/images/rawLogo.png"),
size: SizeConfig.safeBlockHorizontal * 6.7,
),
),
label: ("TESO"),
),
BottomNavigationBarItem(
icon: Icon(
Icons.notifications,
size: SizeConfig.safeBlockHorizontal * 6.7,
),
label: ("Alerts"),
),
BottomNavigationBarItem(
icon: Icon(
Icons.person,
size: SizeConfig.safeBlockHorizontal * 6.7,
),
label: ("Personal"),
),
],
onTap: navigationTapped,
currentIndex: _page,
),
),
),
);
}
}