using System.Collections.ObjectModel; using galacticlip_app.Models; using galacticlip_app.Services; using System.Threading.Tasks; using System.Linq; using Newtonsoft.Json; using System.Windows.Input; namespace galacticlip_app { public class MainPageViewModel : BindableObject { private readonly NasaMediaService _nasaMediaService; public ObservableCollection Images { get; private set; } private string _userName; public string UserName { get => _userName; set { _userName = value; OnPropertyChanged(); } } private string _userProfilePhoto; public string UserProfilePhoto { get => _userProfilePhoto; set { _userProfilePhoto = value; OnPropertyChanged(); } } public ICommand BookmarkCommand { get; } public ICommand ShowDetailsCommand { get; } public MainPageViewModel() { _nasaMediaService = new NasaMediaService(); Images = new ObservableCollection(); UserName = Preferences.Get("UserName", "Guest"); UserProfilePhoto = Preferences.Get("UserProfilePhoto", "Star Explorer"); LoadRandomImages(); BookmarkCommand = new Command(OnBookmarkItem); // Subscribe to bookmark updates AppMessenger.MessageReceived += OnMessageReceived; ShowDetailsCommand = new Command(OnShowDetails); } private async void LoadRandomImages() { var images = await _nasaMediaService.GetRandomImagesAsync(); foreach (var image in images) { Images.Add(image); } RefreshBookmarkStates(); OnPropertyChanged(nameof(Images)); } private void OnBookmarkItem(NasaMediaItem item) { item.IsBookmarked = !item.IsBookmarked; var currentBookmarksJson = Preferences.Get("BookmarkedItems", "[]"); var currentBookmarks = JsonConvert.DeserializeObject>(currentBookmarksJson) ?? new List(); if (item.IsBookmarked) { currentBookmarks.Add(item); } else { currentBookmarks.RemoveAll(b => b.ThumbnailUrl == item.ThumbnailUrl); } var updatedBookmarksJson = JsonConvert.SerializeObject(currentBookmarks); Preferences.Set("BookmarkedItems", updatedBookmarksJson); // Notify other parts of the app AppMessenger.SendMessage("BookmarksUpdated"); } private void RefreshBookmarkStates() { var bookmarkedJson = Preferences.Get("BookmarkedItems", string.Empty); var bookmarkedItems = string.IsNullOrWhiteSpace(bookmarkedJson) ? new List() : JsonConvert.DeserializeObject>(bookmarkedJson); foreach (var image in Images) { image.IsBookmarked = bookmarkedItems.Any(b => b.ThumbnailUrl == image.ThumbnailUrl); } OnPropertyChanged(nameof(Images)); } private void OnMessageReceived(string message) { if (message == "BookmarksUpdated") { RefreshBookmarkStates(); } } ~MainPageViewModel() { AppMessenger.MessageReceived -= OnMessageReceived; } private async void OnShowDetails(NasaMediaItem item) { if (item != null) { // Navigate to MediaDetailPage with the selected item await App.Current.MainPage.Navigation.PushModalAsync(new MediaDetailPage(item)); } } } }