props/Props.Shop/Adafruit/Api/SearchManager.cs

61 lines
2.0 KiB
C#
Raw Normal View History

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using FuzzySharp;
using FuzzySharp.Extractor;
using Props.Shop.Framework;
namespace Props.Shop.Adafruit.Api
{
public class SearchManager : IDisposable
{
public float Similarity { get; set; }
public IProductListingManager ProductListingManager { get; private set; }
private bool disposedValue;
public SearchManager(IProductListingManager productListingManager, float similarity = 0.8f)
{
this.ProductListingManager = productListingManager ?? throw new ArgumentNullException("productListingManager");
this.Similarity = similarity;
}
public async IAsyncEnumerable<ProductListing> Search(string query)
{
// TODO: Implement indexed search.
if (ProductListingManager.ProductListings == null) {
ProductListingManager.RefreshProductListings();
}
IReadOnlyDictionary<string, IList<ProductListing>> productListings = await ProductListingManager.ProductListings;
if (productListings == null) throw new InvalidAsynchronousStateException("productListings can't be null");
foreach (ExtractedResult<string> listingNames in Process.ExtractAll(query, productListings.Keys, cutoff: (int)(Similarity * 100)))
{
foreach (ProductListing same in productListings[listingNames.Value])
{
yield return same;
}
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
ProductListingManager.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}