using Microsoft.Extensions.Configuration; using MP.Core.DTO; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; namespace MP.Data.Services.RouteWeight { public class InMemoryWeightProvider : IWeightProvider { #region Public Constructors public InMemoryWeightProvider(IConfiguration config) { _defaultOld = config.GetValue("RouteMan:DefaultWeightOld", 100); _defaultNew = config.GetValue("RouteMan:DefaultWeightNew", 0); } #endregion Public Constructors #region Public Methods public async Task> GetAllWeightsAsync() { var result = new List(); await Task.Delay(1); foreach (var kvp in _map) { result.Add(new WeightDTO { Method = kvp.Key, OldWeight = Math.Clamp(kvp.Value.oldW, 0, 100), NewWeight = Math.Clamp(kvp.Value.newW, 0, 100) }); } return result; } public (int oldWeight, int newWeight) GetWeightsFor(string method) { if (string.IsNullOrEmpty(method)) method = "unknown"; return _map.GetOrAdd(method, _ => (_defaultOld, _defaultNew)); } public void SetWeights(string method, int oldWeight, int newWeight) { _map[method] = (Math.Clamp(oldWeight, 0, 100), Math.Clamp(newWeight, 0, 100)); } public bool UpsertWeight(WeightDTO updRecord) { if (updRecord == null || string.IsNullOrEmpty(updRecord.Method)) return false; _map[updRecord.Method] = (Math.Clamp(updRecord.OldWeight, 0, 100), Math.Clamp(updRecord.NewWeight, 0, 100)); return true; } #endregion Public Methods #region Private Fields private readonly int _defaultNew; private readonly int _defaultOld; private readonly ConcurrentDictionary _map = new(); #endregion Private Fields } }