72 lines
2.1 KiB
C#
72 lines
2.1 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using FuzzySharp;
|
|
using FuzzySharp.Extractor;
|
|
using Props.Shop.Framework;
|
|
|
|
namespace Props.Shop.Adafruit.Api
|
|
{
|
|
public class SearchManager : IDisposable
|
|
{
|
|
public float Similarity { get; set; }
|
|
private readonly object searchLock = new object();
|
|
private IDictionary<string, IList<ProductListing>> searched;
|
|
private IProductListingManager listingManager;
|
|
private bool disposedValue;
|
|
|
|
public SearchManager(IProductListingManager productListingManager, float similarity = 0.8f)
|
|
{
|
|
this.listingManager = productListingManager ?? throw new ArgumentNullException("productListingManager");
|
|
this.Similarity = similarity;
|
|
listingManager.DataUpdateEvent += OnDataUpdate;
|
|
}
|
|
|
|
private void OnDataUpdate(object sender, EventArgs eventArgs)
|
|
{
|
|
BuildSearchIndex();
|
|
}
|
|
|
|
private void BuildSearchIndex()
|
|
{
|
|
lock (searchLock)
|
|
{
|
|
searched = new Dictionary<string, IList<ProductListing>>(listingManager.ActiveListings);
|
|
}
|
|
}
|
|
|
|
public IEnumerable<ProductListing> Search(string query)
|
|
{
|
|
lock (searchLock)
|
|
{
|
|
foreach (ExtractedResult<string> listingNames in Process.ExtractAll(query, searched.Keys, cutoff: (int)(Similarity * 100)))
|
|
{
|
|
foreach (ProductListing same in searched[listingNames.Value])
|
|
{
|
|
yield return same;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
protected virtual void Dispose(bool disposing)
|
|
{
|
|
if (!disposedValue)
|
|
{
|
|
if (disposing)
|
|
{
|
|
listingManager.Dispose();
|
|
}
|
|
|
|
disposedValue = true;
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Dispose(disposing: true);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
}
|
|
} |