props/Props/Services/Modules/LiveSearchManager.cs

58 lines
2.4 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Castle.Core.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Props.Models.Search;
using Props.Options;
using Props.Shop.Framework;
namespace Props.Services.Modules
{
public class LiveSearchManager : ISearchManager
{
private ILogger<LiveSearchManager> logger;
private SearchOptions searchOptions;
private IShopManager shopManager;
private IMetricsManager metricsManager;
public LiveSearchManager(IMetricsManager metricsManager, IShopManager shopManager, IConfiguration configuration, ILogger<LiveSearchManager> logger)
{
this.logger = logger;
this.metricsManager = metricsManager;
this.shopManager = shopManager;
this.searchOptions = configuration.GetSection(SearchOptions.Search).Get<SearchOptions>();
}
public IEnumerable<ProductListing> Search(string query, SearchOutline searchOutline)
{
if (string.IsNullOrWhiteSpace(query)) throw new ArgumentException($"Query \"{query}\" is null or whitepsace.");
if (searchOutline == null) throw new ArgumentNullException("searchOutline");
List<ProductListing> results = new List<ProductListing>();
metricsManager.RegisterSearchQuery(query);
logger.LogDebug("Searching for \"{0}\".", query);
foreach (string shopName in shopManager.GetAllShopNames())
{
if (searchOutline.Enabled[shopName])
{
logger.LogDebug("Checking \"{0}\".", shopName);
int amount = 0;
foreach (ProductListing product in shopManager.GetShop(shopName).Search(query, searchOutline.Filters))
{
if (searchOutline.Filters.Validate(product))
{
amount += 1;
metricsManager.RegisterListing(product, shopName);
results.Add(product);
}
if (amount >= searchOptions.MaxResults) break;
}
logger.LogDebug("Found {0} listings that satisfy the search filters from {1}.", amount, shopName);
}
}
return results;
}
}
}