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 logger; private SearchOptions searchOptions; public IShopManager ShopManager { get; private set; } private IMetricsManager metricsManager; public LiveSearchManager(IMetricsManager metricsManager, IShopManager shopManager, IConfiguration configuration, ILogger logger) { this.logger = logger; this.metricsManager = metricsManager; this.ShopManager = shopManager; this.searchOptions = configuration.GetSection(SearchOptions.Search).Get(); } public async Task> 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 results = new List(); 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; await 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; } } }