// ignore_for_file: dead_code, unnecessary_null_comparison import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:teso/Classes/API%20Clasess/CouponHead.dart'; import 'package:teso/Classes/Payload.dart'; import 'package:teso/Pages/PageWidgets/Alerts/AlertTile.dart'; import 'package:teso/Pages/PageWidgets/Alerts/Redeemable.dart'; import 'package:teso/Pages/PageWidgets/Alerts/Refund.dart'; import 'package:teso/Pages/PageWidgets/Alerts/personalizedCoupon.dart'; import 'package:teso/Pages/PageWidgets/Alerts/post.dart'; import 'package:teso/Pages/PageWidgets/Alerts/requestTile.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:http/http.dart' as http; import 'package:teso/util/consts.dart'; import 'package:provider/provider.dart'; import 'package:teso/providers/user_provider.dart'; import 'dart:convert'; import 'package:teso/Notifications/NotificationPlugin.dart'; class Alerts extends StatefulWidget { @override _AlertsState createState() => _AlertsState(); } class _AlertsState extends State { List? listMessage = new List.from([]); String? id = ""; int _limit = 20; final int _limitIncrement = 20; final ScrollController listScrollController = ScrollController(); late SharedPreferences prefs; bool loading = false; Icon iconIndicator(String? type) { switch (type) { case "alerts": return Icon( Icons.notifications, color: Colors.grey[50], ); break; case "funds": return Icon( Icons.wallet_giftcard_outlined, color: Colors.grey[50], ); break; case "redeemable": return Icon( Icons.redeem, color: Colors.grey[50], ); break; case "gifted": return Icon( Icons.redeem, color: Colors.grey[50], ); break; case "warning": return Icon( Icons.warning, color: Colors.grey[50], ); break; case "friendapproval": return Icon( Icons.people_alt, color: Colors.grey[50], ); break; default: return Icon( Icons.notifications, color: Colors.grey[50], ); break; } } setTitle(value) { switch (value) { case "friendrequest": return "Friend Request"; default: return ""; } } setDescription(value) { switch (value) { case "friendrequest": return " sent you a friend request"; case "friendapproval": return " accepted your friend request !!!"; default: return ""; } } _scrollListener() { if (listScrollController.offset >= listScrollController.position.maxScrollExtent && !listScrollController.position.outOfRange) { print("reach the bottom"); setState(() { print("reach the bottom"); _limit += _limitIncrement; }); } if (listScrollController.offset <= listScrollController.position.minScrollExtent && !listScrollController.position.outOfRange) { print("reach the top"); setState(() { print("reach the top"); }); } } void initState() { listScrollController.addListener(_scrollListener); SharedPreferences.getInstance().then((value) => id = value.getString("id")); super.initState(); } void approveRelationship(userGUID) async { prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso")!; Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; String? searchValue = userGUID; var register = serverLocation + 'relationships/friendapproval'; var client = await http.post(Uri.parse(register), body: json.encode(searchValue), headers: requestHeaders); if (client.statusCode == 200) { setState(() {}); Provider.of(context, listen: false).loadFriends(); } else { setState(() {}); } } void declineRelationship(userGUID) async { prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso")!; Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; String? searchValue = userGUID; var register = serverLocation + 'relationships/frienddecline'; var client = await http.post(Uri.parse(register), body: json.encode(searchValue), headers: requestHeaders); if (client.statusCode == 200) { setState(() {}); Provider.of(context, listen: false).loadFriends(); } else { setState(() {}); } } void acceptCoupon(CouponsHead head) async { setState(() { loading = true; }); try { prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso")!; Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'coupons/acceptPersonalized'; var client = await http.post(Uri.parse(register), body: json.encode(head), headers: requestHeaders); if (client.statusCode == 200) { } else if (client.statusCode == 400) { Payload payload = new Payload(); payload.loadID = "TESN000"; payload.load1 = "CouponAcquisition"; await notificationPlugin.showNotification( "Offer Expired", "Unable to acquire coupon as this offer has expired!!", payload.toString(), ); } else { Payload payload = new Payload(); payload.loadID = "TESN000"; payload.load1 = "CouponAcquisition"; await notificationPlugin.showNotification( "Error Occurred", "Unable to acquire coupon as this moment", payload.toString(), ); } } catch (e) { print(e); Payload payload = new Payload(); payload.loadID = "TESN000"; payload.load1 = "CouponAcquisition"; await notificationPlugin.showNotification( "Error Occurred", "Unable to acquire coupon as this moment", payload.toString(), ); } setState(() { loading = false; }); } @override Widget build(BuildContext context) { return Scaffold( body: !loading ? Consumer( builder: (BuildContext context, UserProvider value, Widget? child) { if (value != null) { id = value.currentUser!.userGUID; return StreamBuilder( stream: FirebaseFirestore.instance .collection('notifications') .doc(id != null ? id : "") .collection(id != null ? id! : "") .orderBy('timestamp', descending: true) .limit(_limit) .snapshots(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation( Theme.of(context).primaryColor))); } else if (snapshot.data == null) { return Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation( Theme.of(context).primaryColor))); } else { listMessage = snapshot.data!.docs; return ListView.builder( // controller: listScrollController, itemCount: listMessage!.length, itemBuilder: (BuildContext context, int index) { int timeInMillis = int.parse(snapshot .data!.docs[index]['timestamp'] .toString()); DateTime date = DateTime.fromMillisecondsSinceEpoch( timeInMillis); switch (listMessage![index]["notificationType"]) { case "friendrequest": return buildRequest( context: context, approve: () => approveRelationship( listMessage![index]["initiatorID"]), decline: () => declineRelationship( listMessage![index]["initiatorID"]), timestamp: date, description: listMessage![index] ["initiatorUsername"] + setDescription(listMessage![index] ["notificationType"]), thumbnail: listMessage![index] ["initiatorThumbnail"], username: listMessage![index] ["initiatorUsername"], icons: iconIndicator( listMessage![index]["notificationType"], ), ); break; case "redeemable": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index]["couponID"]), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildRedeemableAlert( context: context, timestamp: date, message: listMessage![index]["message"], thumbnail: listMessage![index] ["productImage"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "expired": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index]["couponID"]), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildRedeemableAlert( context: context, timestamp: date, message: listMessage![index]["message"], thumbnail: listMessage![index] ["productImage"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "gifted": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index]["couponID"]), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildRedeemableAlert( context: context, timestamp: date, message: listMessage![index]["message"], thumbnail: listMessage![index] ["productImage"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "likes": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index]["timestamp"] .toString()), background: Container( //height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildAlert( context: context, timestamp: date, username: listMessage![index]["message"], description: listMessage![index] ["message"] + setDescription(listMessage![index] ["notificationType"]), thumbnail: listMessage![index] ["thumbnail"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "comments": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index]["timestamp"] .toString()), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildAlert( context: context, timestamp: date, username: listMessage![index]["message"], description: listMessage![index] ["message"] + setDescription(listMessage![index] ["notificationType"]), thumbnail: listMessage![index] ["thumbnail"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "personalized": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: buildPersonalizedAlert( context: context, timestamp: date, message: listMessage![index]["message"], thumbnail: listMessage![index] ["productImage"], icons: iconIndicator(listMessage![index] ["notificationType"]), decline: () => FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }), accept: () { var coup = jsonDecode( listMessage![index]["coupon"]); CouponsHead head = new CouponsHead(); head.businessId = coup["BusinessId"]; head.couponId = listMessage![index].reference.id; head.expiration = DateTime.parse( coup["Expiration"].toString()); head.lower = coup["LowerLimit"]; head.quantity = 1; head.state = listMessage![index] ["couponCondition"]; head.targetProduct = coup["TargetProduct"]; head.type = coup["Type"]; head.upper = coup["UpperLimit"]; head.generated = DateTime.parse( coup["Generated"].toString()); acceptCoupon(head); }), ); break; case "cancellation": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index].reference.id), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildRedeemableAlert( context: context, timestamp: date, message: listMessage![index]["message"], thumbnail: listMessage![index] ["productImage"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "refund": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index].reference.id), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildRefundAlert( context: context, timestamp: date, message: listMessage![index]["message"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "welcome": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index].reference.id), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildRefundAlert( context: context, timestamp: date, message: listMessage![index]["message"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "adStatus": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index].reference.id), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildPostAlert( context: context, timestamp: date, message: listMessage![index]["message"], thumbnail: listMessage![index] ["assetID"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; case "desire": return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key(listMessage![index]["couponID"]), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildRedeemableAlert( context: context, timestamp: date, message: listMessage![index]["message"], thumbnail: listMessage![index] ["productImage"], icons: iconIndicator(listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); break; default: try { return Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Dismissible( key: Key( listMessage![index]["relationID"]), background: Container( height: 100, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ darkAccent, accentMain, ], ), ), child: Center( child: Text( "Cleared!!!!", style: TextStyle( color: Colors.white, fontSize: 25), ), ), ), child: buildAlert( context: context, timestamp: date, username: listMessage![index] ["initiatorUsername"], description: listMessage![index] ["initiatorUsername"] + setDescription(listMessage![index] ["notificationType"]), thumbnail: listMessage![index] ["initiatorThumbnail"], icons: iconIndicator( listMessage![index] ["notificationType"]), ), onDismissed: (direction) { FirebaseFirestore.instance .runTransaction( (transaction) async { transaction.delete( listMessage![index].reference); }); }), ); } catch (e) { print(e); return Container(); } break; } }, ); } }, ); } else { return Center( child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation( Theme.of(context).primaryColor))); } }, ) : Container( padding: EdgeInsets.only(top: MediaQuery.of(context).size.width * 0.7), height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: Center( child: Column( children: [ CupertinoActivityIndicator( animating: true, radius: 15, ), Text("Processing request....."), ], ), ), ), ); } }