| | 1 | | using TMPro; |
| | 2 | | using UnityEngine; |
| | 3 | |
|
| | 4 | | /// <summary> |
| | 5 | | /// Shows the number of unread messages from a friend. |
| | 6 | | /// </summary> |
| | 7 | | public class UnreadNotificationBadge : MonoBehaviour |
| | 8 | | { |
| | 9 | | public TextMeshProUGUI notificationText; |
| | 10 | | public GameObject notificationContainer; |
| 79 | 11 | | public int maxNumberToShow = 9; |
| | 12 | |
|
| | 13 | | private IChatController chatController; |
| | 14 | | private string currentUserId; |
| | 15 | | private int currentUnreadMessagesValue; |
| | 16 | | private bool isInitialized; |
| | 17 | |
|
| | 18 | | public int CurrentUnreadMessages |
| | 19 | | { |
| 0 | 20 | | get => currentUnreadMessagesValue; |
| | 21 | | set |
| | 22 | | { |
| 106 | 23 | | currentUnreadMessagesValue = value; |
| | 24 | |
|
| 106 | 25 | | if (currentUnreadMessagesValue > 0) |
| | 26 | | { |
| 13 | 27 | | notificationContainer.SetActive(true); |
| 13 | 28 | | notificationText.text = currentUnreadMessagesValue <= maxNumberToShow ? currentUnreadMessagesValue.ToStr |
| 13 | 29 | | } |
| | 30 | | else |
| | 31 | | { |
| 93 | 32 | | notificationContainer.SetActive(false); |
| | 33 | | } |
| 93 | 34 | | } |
| | 35 | | } |
| | 36 | |
|
| | 37 | | /// <summary> |
| | 38 | | /// Prepares the notification badge for listening to a specific user |
| | 39 | | /// </summary> |
| | 40 | | /// <param name="chatController">Chat Controlled to be listened</param> |
| | 41 | | /// <param name="userId">User ID to listen to</param> |
| | 42 | | public void Initialize(IChatController chatController, string userId) |
| | 43 | | { |
| 72 | 44 | | if (chatController == null) |
| 3 | 45 | | return; |
| | 46 | |
|
| 69 | 47 | | this.chatController = chatController; |
| 69 | 48 | | currentUserId = userId; |
| | 49 | |
|
| 69 | 50 | | UpdateUnreadMessages(); |
| | 51 | |
|
| 69 | 52 | | chatController.OnUserUnseenMessagesUpdated += HandleUnseenMessagesUpdated; |
| | 53 | |
|
| 69 | 54 | | isInitialized = true; |
| 69 | 55 | | } |
| | 56 | |
|
| | 57 | | private void HandleUnseenMessagesUpdated(string userId, int unseenMessages) |
| | 58 | | { |
| 18 | 59 | | if (userId != currentUserId) return; |
| 14 | 60 | | CurrentUnreadMessages = unseenMessages; |
| 14 | 61 | | } |
| | 62 | |
|
| | 63 | | private void OnEnable() |
| | 64 | | { |
| 237 | 65 | | if (!isInitialized) return; |
| 23 | 66 | | UpdateUnreadMessages(); |
| 23 | 67 | | } |
| | 68 | |
|
| | 69 | | private void OnDestroy() |
| | 70 | | { |
| 44 | 71 | | if (chatController != null) |
| 38 | 72 | | chatController.OnUserUnseenMessagesUpdated -= HandleUnseenMessagesUpdated; |
| 44 | 73 | | } |
| | 74 | |
|
| 92 | 75 | | private void UpdateUnreadMessages() => CurrentUnreadMessages = chatController.GetAllocatedUnseenMessages(currentUser |
| | 76 | | } |