Last active
October 25, 2023 17:40
-
-
Save KyleT-bone/306b57e0a88657d6bed30beda92e9935 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.glucocare; | |
import android.app.Dialog; | |
import android.content.Context; | |
import android.content.DialogInterface; | |
import android.content.SharedPreferences; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Button; | |
import android.widget.ImageView; | |
import android.widget.TextView; | |
import androidx.fragment.app.Fragment; | |
import androidx.recyclerview.widget.RecyclerView; | |
import com.google.firebase.FirebaseApp; | |
import com.google.firebase.auth.FirebaseAuth; | |
import com.google.firebase.database.DatabaseReference; | |
import com.google.firebase.database.FirebaseDatabase; | |
import com.google.firebase.firestore.DocumentReference; | |
import com.google.firebase.firestore.DocumentSnapshot; | |
import com.google.firebase.firestore.FirebaseFirestore; | |
import com.google.firebase.firestore.QueryDocumentSnapshot; | |
import com.google.firebase.firestore.QuerySnapshot; | |
import com.google.firebase.firestore.SetOptions; | |
import java.text.SimpleDateFormat; | |
import java.util.Calendar; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.Locale; | |
import java.util.Map; | |
/** | |
* A simple {@link Fragment} subclass. | |
* Use the {@link RewardsFragment#newInstance} factory method to | |
* create an instance of this fragment. | |
* | |
*/ | |
public class RewardsFragment extends Fragment { | |
// TODO: Rename parameter arguments, choose names that match | |
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER | |
private static final String ARG_PARAM1 = "param1"; | |
private static final String ARG_PARAM2 = "param2"; | |
// TODO: Rename and change types of parameters | |
private String mParam1; | |
private String mParam2; | |
private RecyclerView recyclerView; | |
private int couponsEarned = 0; | |
private boolean couponEarned = false; | |
private LogAdapter logAdapter; | |
ImageView bronzeMedalImageView; | |
ImageView silverMedalImageView; | |
ImageView goldMedalImageView; | |
private int logsToday = 0; | |
Button bronzeDiscountBtn, silverDiscountBtn, goldDiscountBtn, rewardPer500PointsBtn; | |
Calendar calendar; | |
int currentDay, lastDay; | |
TextView bronzeText, silverText, goldText; | |
TextView totalLogsText, totalLogsTodayText, scoreText, rewardPer500PointsText; | |
FirebaseFirestore db; | |
Long userScore; | |
// Add this member variable | |
private DatabaseReference userScoreRef; | |
/** | |
* Use this factory method to create a new instance of | |
* this fragment using the provided parameters. | |
* | |
* @param param1 Parameter 1. | |
* @param param2 Parameter 2. | |
* @return A new instance of fragment RewardsFragment. | |
*/ | |
// TODO: Rename and change types and number of parameters | |
public static RewardsFragment newInstance(String param1, String param2) { | |
RewardsFragment fragment = new RewardsFragment(); | |
Bundle args = new Bundle(); | |
args.putString(ARG_PARAM1, param1); | |
args.putString(ARG_PARAM2, param2); | |
fragment.setArguments(args); | |
return fragment; | |
} | |
public RewardsFragment() { | |
// Required empty public constructor | |
} | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
if (getArguments() != null) { | |
mParam1 = getArguments().getString(ARG_PARAM1); | |
mParam2 = getArguments().getString(ARG_PARAM2); | |
} | |
FirebaseApp.initializeApp(getContext()); | |
userScoreRef = FirebaseDatabase.getInstance().getReference().child("user_scores"); | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, | |
Bundle savedInstanceState) { | |
View rootView = inflater.inflate(R.layout.fragment_rewards, container, false); | |
db = FirebaseFirestore.getInstance(); | |
// Get the currently logged-in user ID | |
String currentUserId = getCurrentUserId(); | |
// Add the code snippet to check for a new day | |
calendar = Calendar.getInstance(); | |
currentDay = calendar.get(Calendar.DAY_OF_MONTH); | |
SharedPreferences settings = getContext().getSharedPreferences("PREFS", 0); | |
lastDay = settings.getInt("day", 0); | |
if (lastDay != currentDay) { | |
// The app is launched on a new day, perform actions here | |
// For example, you might want to reset the logsToday variable to 0 | |
logsToday = 0; | |
// Update the lastDay value in SharedPreferences to the current day | |
SharedPreferences.Editor editor = settings.edit(); | |
editor.putInt("day", currentDay); | |
editor.apply(); | |
} | |
// Call the method to fetch the total number of blood sugar logs for the current user | |
fetchTotalBloodSugarLogs(currentUserId); | |
fetchUserScoreAndUpdateUI(currentUserId); | |
scoreText = rootView.findViewById(R.id.scoreText); | |
totalLogsText = rootView.findViewById(R.id.totalLogsText); | |
totalLogsTodayText = rootView.findViewById(R.id.totalLogsTodayText); | |
bronzeMedalImageView = rootView.findViewById(R.id.bronzeMedal); | |
silverMedalImageView = rootView.findViewById(R.id.silverMedal); | |
goldMedalImageView = rootView.findViewById(R.id.goldMedal); | |
bronzeDiscountBtn = rootView.findViewById(R.id.bronzeCouponBtn); | |
silverDiscountBtn = rootView.findViewById(R.id.silverCouponBtn); | |
goldDiscountBtn = rootView.findViewById(R.id.goldCouponBtn); | |
rewardPer500PointsBtn = rootView.findViewById(R.id.rewardPer500PointsBtn); | |
rewardPer500PointsBtn.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
showCouponAfterMedalsReward(); | |
} | |
}); | |
rewardPer500PointsText = rootView.findViewById(R.id.rewardPer500PointsText); | |
bronzeDiscountBtn.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { showBronzeCouponReward(); } | |
}); | |
silverDiscountBtn.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { showSilverCouponReward(); } | |
}); | |
goldDiscountBtn.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { showGoldCouponReward(); } | |
}); | |
bronzeText = rootView.findViewById(R.id.bronzeText); | |
silverText = rootView.findViewById(R.id.silverText); | |
goldText = rootView.findViewById(R.id.goldText); | |
updateMedalImages(); | |
return rootView; | |
} | |
private void fetchTotalBloodSugarLogs(String currentUserId) { | |
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date()); | |
// Total | |
db.collection("bloodSugar") | |
.whereEqualTo("userId", currentUserId) | |
.get() | |
.addOnCompleteListener(task -> { | |
if (task.isSuccessful()) { | |
int totalLogs = 0; | |
for (QueryDocumentSnapshot document : task.getResult()) { | |
totalLogs++; | |
// Check if the log is for today | |
String logDate = document.getString("date"); | |
if (logDate != null && logDate.equals(currentDate)) { | |
logsToday++; | |
} | |
} | |
totalLogsText.setText("Total logs: " + totalLogs); | |
totalLogsTodayText.setText("Total logs today: " + logsToday); | |
} | |
}); | |
} | |
private void fetchUserScoreAndUpdateUI(String currentUserId) { | |
// Reference to the user's document in the "userScores" collection | |
DocumentReference userScoreDocRef = db.collection("userScores").document(currentUserId); | |
userScoreDocRef.get() | |
.addOnCompleteListener(task -> { | |
if (task.isSuccessful()) { | |
DocumentSnapshot document = task.getResult(); | |
if (document.exists()) { | |
userScore = document.getLong("score"); | |
boolean isBronzeUnlocked = document.getBoolean("bronzeMedal"); | |
boolean isSilverUnlocked = document.getBoolean("silverMedal"); | |
boolean isGoldUnlocked = document.getBoolean("goldMedal"); | |
// Update the UI with the user's score and medal states | |
scoreText.setText("Score: " + userScore); | |
if (isBronzeUnlocked) { | |
unlockBronzeMedal(); | |
} else { | |
lockBronzeMedal(); | |
} | |
if (isSilverUnlocked) { | |
unlockSilverMedal(); | |
} else { | |
lockSilverMedal(); | |
} | |
if (isGoldUnlocked) { | |
unlockGoldMedal(); | |
} else { | |
lockGoldMedal(); | |
} | |
} else { | |
// Handle the case when the document doesn't exist | |
updateUserScoreInFirestore(currentUserId, 0); | |
} | |
} else { | |
// Handle errors here | |
Log.e("Firestore", "Error fetching document: " + task.getException()); | |
} | |
}); | |
} | |
// Method to add or update the user's score in Firestore | |
private void updateUserScoreInFirestore(String userId, long initialScore) { | |
// Reference to the user's document in the "userScores" collection | |
DocumentReference userScoreDocRef = db.collection("userScores").document(userId); | |
// Create a map with the data you want to set (e.g., score and medals) | |
Map<String, Object> userData = new HashMap<>(); | |
userData.put("score", initialScore); // Replace "score" with the actual field name | |
userData.put("bronzeMedal", userScore >= 200); // Check if the user unlocked the bronze medal | |
userData.put("silverMedal", userScore >= 500); // Check if the user unlocked the silver medal | |
userData.put("goldMedal", userScore >= 2000); // Check if the user unlocked the gold medal | |
// Use SetOptions to specify that the document should be created if it doesn't exist | |
SetOptions options = SetOptions.merge(); // Use merge to update the document if it exists | |
fetchUserScoreAndUpdateUI(userId); | |
userScoreDocRef.set(userData, options) | |
.addOnCompleteListener(task -> { | |
if (task.isSuccessful()) { | |
Log.d("Firestore", "Document successfully added or updated."); | |
} else { | |
// Handle errors here | |
Log.e("Firestore", "Error adding or updating document: " + task.getException()); | |
} | |
}); | |
} | |
// Method to get the currently logged-in user ID | |
private String getCurrentUserId() { | |
FirebaseAuth auth = FirebaseAuth.getInstance(); | |
if (auth.getCurrentUser() != null) { | |
return auth.getCurrentUser().getUid(); | |
} else { | |
// Return an empty string or handle the case when the user is not logged in | |
return ""; | |
} | |
} | |
// Medals | |
private void setMedalState(String medalName, boolean unlocked) { | |
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("Medals", Context.MODE_PRIVATE); | |
SharedPreferences.Editor editor = sharedPreferences.edit(); | |
editor.putBoolean(medalName, unlocked); | |
editor.apply(); | |
} | |
private void updateMedalImages() { | |
if (isAdded()) { | |
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("Medals", Context.MODE_PRIVATE); | |
boolean isBronzeUnlocked = sharedPreferences.getBoolean("bronzeMedal", false); | |
boolean isSilverUnlocked = sharedPreferences.getBoolean("silverMedal", false); | |
boolean isGoldUnlocked = sharedPreferences.getBoolean("goldMedal", false); | |
if (!isBronzeUnlocked) { | |
if (userScore != null && userScore >= 200) { // Check if the user unlocked the bronze medal | |
unlockBronzeMedal(); | |
setMedalState("bronzeMedal", true); // Update medal state | |
} else { | |
lockBronzeMedal(); | |
} | |
} else { | |
unlockBronzeMedal(); | |
} | |
if (!isSilverUnlocked) { | |
if (userScore != null && userScore >= 500) { // Check if the user unlocked the silver medal | |
unlockSilverMedal(); | |
setMedalState("silverMedal", true); // Update medal state | |
} else { | |
lockSilverMedal(); | |
} | |
} else { | |
unlockSilverMedal(); | |
} | |
if (!isGoldUnlocked) { | |
if (userScore != null && userScore >= 2000) { // Check if the user unlocked the gold medal | |
unlockGoldMedal(); | |
setMedalState("goldMedal", true); // Update medal state | |
} else { | |
lockGoldMedal(); | |
} | |
} else { | |
unlockGoldMedal(); | |
} | |
} | |
} | |
public void showBronzeCouponReward() { | |
Dialog myDialog = new Dialog(getContext()); | |
myDialog.setContentView(R.layout.coupon_bronze_reward); | |
Button closeButton = myDialog.findViewById(R.id.closeButton); | |
closeButton.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
myDialog.dismiss(); | |
} | |
}); | |
myDialog.show(); | |
} | |
private void unlockBronzeMedal() { | |
bronzeMedalImageView.setImageResource(R.drawable.bronze_unlocked); | |
bronzeText.setVisibility(View.INVISIBLE); | |
bronzeDiscountBtn.setVisibility(View.VISIBLE); | |
} | |
private void lockBronzeMedal() { | |
bronzeMedalImageView.setImageResource(R.drawable.bronze_locked); | |
bronzeText.setVisibility(View.VISIBLE); | |
bronzeDiscountBtn.setVisibility(View.INVISIBLE); | |
} | |
public void showSilverCouponReward() { | |
Dialog myDialog = new Dialog(getContext()); | |
myDialog.setContentView(R.layout.coupon_silver_reward); | |
Button closeButton = myDialog.findViewById(R.id.closeButton); | |
closeButton.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
myDialog.dismiss(); | |
} | |
}); | |
myDialog.show(); | |
} | |
private void unlockSilverMedal() { | |
silverMedalImageView.setImageResource(R.drawable.silver_unlocked); | |
silverText.setVisibility(View.INVISIBLE); | |
silverDiscountBtn.setVisibility(View.VISIBLE); | |
bronzeDiscountBtn.setVisibility(View.INVISIBLE); | |
} | |
private void lockSilverMedal() { | |
silverMedalImageView.setImageResource(R.drawable.silver_locked); | |
silverText.setVisibility(View.VISIBLE); | |
silverDiscountBtn.setVisibility(View.INVISIBLE); | |
} | |
public void showGoldCouponReward() { | |
Dialog myDialog = new Dialog(getContext()); | |
myDialog.setContentView(R.layout.coupon_gold_reward); | |
Button closeButton = myDialog.findViewById(R.id.closeButton); | |
closeButton.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
myDialog.dismiss(); | |
} | |
}); | |
myDialog.show(); | |
} | |
private void unlockGoldMedal() { | |
goldMedalImageView.setImageResource(R.drawable.gold_unlocked); | |
goldText.setVisibility(View.INVISIBLE); | |
goldDiscountBtn.setVisibility(View.VISIBLE); | |
silverDiscountBtn.setVisibility(View.INVISIBLE); | |
bronzeDiscountBtn.setVisibility(View.INVISIBLE); | |
rewardPer500PointsText.setVisibility(View.VISIBLE); | |
Long remainingPoints = 500 - (userScore % 500); | |
if ((remainingPoints == 500) || (userScore >= 2500) && (isCouponEarned() == true)) { | |
rewardPer500PointsText.setText("Claim your coupon!"); | |
rewardPer500PointsBtn.setVisibility(View.VISIBLE); | |
} else { | |
rewardPer500PointsText.setText("There are " + remainingPoints + " points left to get a coupon"); | |
rewardPer500PointsBtn.setVisibility(View.INVISIBLE); | |
} | |
} | |
private void lockGoldMedal() { | |
goldMedalImageView.setImageResource(R.drawable.gold_locked); | |
goldText.setVisibility(View.VISIBLE); | |
goldDiscountBtn.setVisibility(View.INVISIBLE); | |
rewardPer500PointsText.setVisibility(View.INVISIBLE); | |
rewardPer500PointsBtn.setVisibility(View.INVISIBLE); | |
} | |
private boolean isCouponEarned() { | |
SharedPreferences settings = getContext().getSharedPreferences("PREFS", 0); | |
return settings.getBoolean("couponEarned", false); | |
} | |
public void showCouponAfterMedalsReward() { | |
Dialog myDialog = new Dialog(getContext()); | |
myDialog.setContentView(R.layout.coupon_after_medals_reward); | |
Long remainingPoints = 500 - (userScore % 500); | |
// Customize the coupon dialog as needed, e.g., display the €10 coupon code | |
Button closeButton = myDialog.findViewById(R.id.closeButton); | |
closeButton.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
myDialog.dismiss(); | |
// Update UI to hide the coupon button until the next 500 points | |
rewardPer500PointsBtn.setVisibility(View.INVISIBLE); | |
rewardPer500PointsText.setText("There are " + remainingPoints + " points left to get a coupon"); | |
} | |
}); | |
myDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { | |
@Override | |
public void onCancel(DialogInterface dialogInterface) { | |
// Update UI to hide the coupon button until the next 500 points | |
rewardPer500PointsBtn.setVisibility(View.INVISIBLE); | |
rewardPer500PointsText.setText("There are " + remainingPoints + " points left to get a coupon"); | |
} | |
}); | |
myDialog.show(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment