using System.Collections.ObjectModel;
using QuiverLauncher.Models;
using QuiverLauncher.Services;
namespace QuiverLauncher.ViewModels;
///
/// Browse: the quiverlauncher.com catalog, searched and filtered on the site and read a page at
/// a time, or the player's own app list (a JSON file or URL), filtered here.
///
public sealed class BrowseViewModel(QuiverCatalogClient client, Func> library,
Func customListLocation, Func Apps, string? Error)>> loadCustomList) : ObservableViewModel
{
private string? _cursor;
private int _generation;
private bool _isLoading;
private bool _isLoadingMore;
private string _status = "";
private bool _showingCustomList;
private List? _customApps;
private string? _customAppsLocation;
private Dictionary _consoleNames = [];
private int _total;
private int _catalogTotal;
private readonly Dictionary _games = new(StringComparer.OrdinalIgnoreCase);
public ObservableCollection Items { get; } = [];
/// Original games a search matched, shown above the apps as on the website (at most four).
public ObservableCollection Games { get; } = [];
public bool HasGames => Games.Count > 0;
public IReadOnlyList Consoles { get; private set; } = [];
public string Search { get; set; } = "";
public string Sort { get; set; } = "added";
public string? Platform { get; set; } = BrowseText.CurrentPlatform;
/// A console id, or "maker:Brand" for every console a maker made.
public string? Console { get; set; }
public string? ProjectType { get; set; }
/// "no-generated" or "no-ai" hides apps by AI use; null shows every app.
public string? Ai { get; set; }
/// How many apps the catalog has, or the player's list when it shows.
public int Total { get => _total; private set => Set(ref _total, value); }
public bool HasCustomList => !string.IsNullOrWhiteSpace(customListLocation());
public bool ShowingCustomList { get => _showingCustomList && HasCustomList; set => Set(ref _showingCustomList, value); }
public bool HasFilters => Platform != BrowseText.CurrentPlatform || Console != null || ProjectType != null;
public bool IsLoading { get => _isLoading; private set => Set(ref _isLoading, value); }
public bool IsLoadingMore { get => _isLoadingMore; private set => Set(ref _isLoadingMore, value); }
public bool CanLoadMore => _cursor != null && !IsLoading && !IsLoadingMore && !ShowingCustomList;
/// Why nothing shows: an error, or an empty result.
public string Status { get => _status; private set => Set(ref _status, value); }
/// Clears the search and filters, like the website's Clear filters; the AI filter is a preference and stays.
public void ClearFilters()
{
Search = "";
Platform = BrowseText.CurrentPlatform;
Console = null;
ProjectType = null;
}
/// A maker's heading in the console list, as the website words it.
public static string BrandName(string brand) => brand == "OtherPlatforms" ? "Other platforms" : brand;
public static string AllOfBrand(string brand) => brand == "OtherPlatforms" ? "All other platforms" : $"All {brand}";
/// Loads the first page for the current search and filters, replacing the cards.
public async Task ReloadAsync(CancellationToken token)
{
var generation = ++_generation;
_cursor = null;
IsLoading = true;
IsLoadingMore = false;
Status = "";
Notify(nameof(CanLoadMore));
Items.Clear();
if (Games.Count > 0)
{
Games.Clear();
Notify(nameof(HasGames));
}
try
{
if (ShowingCustomList)
{
await LoadCustomListAsync(generation, token);
return;
}
if (Consoles.Count == 0) await LoadFacetsAsync(token);
Total = _catalogTotal;
var query = new QuiverCatalogQuery(Search, Platform, Console, ProjectType, Sort, Ai);
var page = await client.GetAppsAsync(query, null, token);
if (generation != _generation) return;
Show(page);
if (Items.Count == 0)
{
Status = "Nothing matches that search and those filters.";
// Usage data: what players look for and don't find, by length only (never the words typed).
Telemetry.Current.Track("search_no_results", new Dictionary
{
["query_length"] = Search.Trim().Length,
["filtered"] = query.Os != BrowseText.CurrentPlatform || query.Console != null || query.ProjectType != null || query.Ai != null,
});
}
_ = FindGamesAsync(generation, page.Items, token);
}
catch (Exception ex) when (generation == _generation && !token.IsCancellationRequested)
{
Telemetry.Current.Track("catalog_load_failed", new Dictionary { ["reason"] = Telemetry.ReasonOf(ex) });
Status = $"Couldn't reach quiverlauncher.com. {ex.Message}";
}
finally
{
if (generation == _generation)
{
IsLoading = false;
Notify(nameof(CanLoadMore));
}
}
}
/// A game and every app that plays it, read once per session.
public async Task GetGameAsync(string slug, CancellationToken token)
{
if (_games.TryGetValue(slug, out var known)) return known;
var game = await client.GetGameAsync(slug, token);
if (game != null) game.Entries.Sort(BrowseText.ByPlayerFeedback);
return _games[slug] = game;
}
// The games a search matched: from the apps it found, the games whose title has every word searched for.
private async Task FindGamesAsync(int generation, IReadOnlyList apps, CancellationToken token)
{
var search = Search.Trim();
if (search.Length < 2) return;
var matched = apps.SelectMany(a => a.Games).Where(g => !string.IsNullOrWhiteSpace(g.Slug) && BrowseText.TitleMatches(g.Title, search))
.DistinctBy(g => g.Slug, StringComparer.OrdinalIgnoreCase).Take(4).ToList();
if (matched.Count == 0) return;
try
{
var details = await Task.WhenAll(matched.Select(g => GetGameAsync(g.Slug, token)));
if (generation != _generation) return;
foreach (var detail in details)
if (detail is { Entries.Count: > 0 } found)
Games.Add(new BrowseGame(found.Game.Slug, found.Game.Title, BrowseGame.ArtFor(found.Game), found.Entries.Count));
Notify(nameof(HasGames));
}
// The apps still show; the games row is a shortcut to them.
catch (Exception ex) when (!token.IsCancellationRequested)
{
System.Diagnostics.Debug.WriteLine($"Matching games unavailable: {ex.Message}");
}
}
/// Appends the next page of the catalog, if there is one.
public async Task LoadMoreAsync(CancellationToken token)
{
if (!CanLoadMore) return false;
var generation = _generation;
IsLoadingMore = true;
Notify(nameof(CanLoadMore));
try
{
var query = new QuiverCatalogQuery(Search, Platform, Console, ProjectType, Sort, Ai);
var page = await client.GetAppsAsync(query, _cursor, token);
if (generation != _generation) return false;
Show(page);
Status = "";
return page.Items.Count > 0;
}
catch (Exception ex) when (generation == _generation && !token.IsCancellationRequested)
{
Status = $"Couldn't load more apps. {ex.Message}";
return false;
}
finally
{
if (generation == _generation)
{
IsLoadingMore = false;
Notify(nameof(CanLoadMore));
}
}
}
/// Marks the cards of apps already in the library.
public void RefreshLibraryState() => MarkLibraryState(Items);
/// Marks cards whose app is already in the library: these, or a game page's.
public void MarkLibraryState(IEnumerable items)
{
var apps = library();
var folders = apps.Select(a => a.FolderName?.Trim()).Where(f => !string.IsNullOrEmpty(f))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var item in items)
item.InLibrary = item.ListApp != null
? LibraryAddService.FindExisting(apps, item.ListApp) != null
: folders.Contains(item.FolderName.Trim());
}
/// A game's apps as cards, best first, as on its page.
public List CardsFor(QuiverCatalogGameDetail game)
{
var cards = game.Entries.Select(app => BrowseItem.FromCatalog(app, _consoleNames)).ToList();
MarkLibraryState(cards);
return cards;
}
/// A console's name, as the catalog lists it.
public string ConsoleName(string id) => _consoleNames.GetValueOrDefault(id, id.ToUpperInvariant());
/// The library app a card stands for, once its repository is known.
public GameInfo? FindInLibrary(GameInfo app) => LibraryAddService.FindExisting(library(), app);
/// Forgets the player's list, so a changed location or file is read again.
public void ForgetCustomList()
{
// A load still reading the old list is dropped, so it can't show after the change.
++_generation;
_cursor = null;
_customApps = null;
_customAppsLocation = null;
IsLoading = false;
IsLoadingMore = false;
Status = "";
Items.Clear();
Notify(nameof(CanLoadMore));
Notify(nameof(HasCustomList));
Notify(nameof(ShowingCustomList));
}
private void Show(QuiverCatalogPage page)
{
foreach (var app in page.Items)
Items.Add(BrowseItem.FromCatalog(app, _consoleNames));
_cursor = page.NextCursor;
RefreshLibraryState();
}
private async Task LoadFacetsAsync(CancellationToken token)
{
try
{
var facets = await client.GetFacetsAsync(token);
Consoles = facets.Consoles;
_catalogTotal = facets.Total;
_consoleNames = facets.Consoles.ToDictionary(c => c.Id, c => c.Name, StringComparer.OrdinalIgnoreCase);
}
// Without console names the cards show console ids; the catalog itself still loads.
catch (Exception ex) when (!token.IsCancellationRequested)
{
System.Diagnostics.Debug.WriteLine($"Catalog facets unavailable: {ex.Message}");
}
}
private async Task LoadCustomListAsync(int generation, CancellationToken token)
{
var location = customListLocation().Trim();
if (_customApps == null || _customAppsLocation != location)
{
var (apps, error) = await loadCustomList(location);
token.ThrowIfCancellationRequested();
if (generation != _generation) return;
if (error != null)
{
Status = $"Couldn't read your app list. {error}";
return;
}
_customApps = apps;
_customAppsLocation = location;
}
Total = _customApps.Count;
var search = Search.Trim();
foreach (var app in _customApps.Where(a => search.Length == 0 || AppSearch.Matches(a, search))
.OrderBy(a => a.DisplayName, StringComparer.OrdinalIgnoreCase))
Items.Add(BrowseItem.FromList(app));
RefreshLibraryState();
if (Items.Count == 0)
Status = _customApps.Count == 0 ? "Your app list has no apps." : "Nothing in your app list matches that search.";
}
}