using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Driver;
using StardewModdingAPI.Toolkit.Framework.Clients.Wiki;
namespace StardewModdingAPI.Web.Framework.Caching.Wiki
{
/// Encapsulates logic for accessing the wiki data cache.
internal class WikiCacheRepository : BaseCacheRepository, IWikiCacheRepository
{
/*********
** Fields
*********/
/// The collection for wiki metadata.
private readonly IMongoCollection WikiMetadata;
/// The collection for wiki mod data.
private readonly IMongoCollection WikiMods;
/*********
** Public methods
*********/
/// Construct an instance.
/// The authenticated MongoDB database.
public WikiCacheRepository(IMongoDatabase database)
{
// get collections
this.WikiMetadata = database.GetCollection("wiki-metadata");
this.WikiMods = database.GetCollection("wiki-mods");
// add indexes if needed
this.WikiMods.Indexes.CreateOne(new CreateIndexModel(Builders.IndexKeys.Ascending(p => p.ID)));
}
/// Get the cached wiki metadata.
/// The fetched metadata.
public bool TryGetWikiMetadata(out CachedWikiMetadata metadata)
{
metadata = this.WikiMetadata.Find("{}").FirstOrDefault();
return metadata != null;
}
/// Get the cached wiki mods.
/// A filter to apply, if any.
public IEnumerable GetWikiMods(Expression> filter = null)
{
return filter != null
? this.WikiMods.Find(filter).ToList()
: this.WikiMods.Find("{}").ToList();
}
/// Save data fetched from the wiki compatibility list.
/// The current stable Stardew Valley version.
/// The current beta Stardew Valley version.
/// The mod data.
/// The stored metadata record.
/// The stored mod records.
public void SaveWikiData(string stableVersion, string betaVersion, IEnumerable mods, out CachedWikiMetadata cachedMetadata, out CachedWikiMod[] cachedMods)
{
cachedMetadata = new CachedWikiMetadata(stableVersion, betaVersion);
cachedMods = mods.Select(mod => new CachedWikiMod(mod)).ToArray();
this.WikiMods.DeleteMany("{}");
this.WikiMods.InsertMany(cachedMods);
this.WikiMetadata.DeleteMany("{}");
this.WikiMetadata.InsertOne(cachedMetadata);
}
}
}