using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace CAPI.Custom { public class LeadTime : IComparable { public string OriginalValue { get; protected set; } public string Unit { get; protected set; } public int Value {get; protected set; } public LeadTime(string stringValue) { OriginalValue = stringValue?.Trim(); Value = LeadTimeUnits.ParseValue(stringValue); Unit = LeadTimeUnits.ParseUnit(stringValue); if (Value == 0) Unit = LeadTimeUnits.Stock; } public override string ToString() { if (LeadTimeUnits.Stock.Equals(Unit)) return Unit; var postfix = Value == 1 ? string.Empty : "s"; return $"{Value} {Unit}{postfix}"; } public int CompareTo(LeadTime other) { return this.ToTimeSpan().CompareTo(other.ToTimeSpan()); } public TimeSpan ToTimeSpan() { return LeadTimeUnits.GetTimeSpanFromUnit(Unit) .Multiply(Value); } } public class LeadTimeUnits { public static string Stock => "STOCK"; public static string Hours => "Hour"; public static string Days => "Day"; public static string Weeks => "Week"; public static string Months => "Month"; public static string[] GetSorted => new string[] { Stock, Hours, Days, Weeks, Months }; static Dictionary unitInfos = new Dictionary() { { Months, new LeadTimeUnitInfo { Name = Months, Alternates = new string[]{ "mos", "m" } } }, { Weeks, new LeadTimeUnitInfo { Name = Weeks, Alternates = new string[]{ "w" }, TimeSpan = new TimeSpan(days: 7, 0, 0, 0) } }, { Days, new LeadTimeUnitInfo { Name = Days, Alternates = new string[]{ "d" }, TimeSpan = new TimeSpan(days: 1, 0, 0, 0) } }, { Hours, new LeadTimeUnitInfo { Name = Hours, Alternates = new string[]{ "hrs", "hr", "h" }, TimeSpan = new TimeSpan(hours: 1, 0, 0) } }, { Stock, new LeadTimeUnitInfo { Name = Stock, Alternates = new string[]{ }, TimeSpan = new TimeSpan() } } }; public static TimeSpan GetTimeSpanFromUnit(string unit) { if (!GetSorted.Contains(unit)) return new TimeSpan(); if (Months.Equals(unit, StringComparison.OrdinalIgnoreCase)) { return DateTime.Today.AddMonths(1).Subtract(DateTime.Today); } return unitInfos[unit].TimeSpan; } static Regex regexInt = new Regex(@"\d+"); public static int ParseValue(string value) { var matches = regexInt.Matches(value) .Cast() .Select(m => m.Value.TryParseInt()) .Where(p => p.HasValue); return matches.Max().GetValueOrDefault(); } public static string ParseUnit(string value) { string result = string.Empty; if (value.IsEmpty()) return Stock; foreach (var key in LeadTimeUnits.GetSorted.Reverse()) { if (result.IsEmpty()) { if (value.ToLower().Contains(key.ToLower())) { result = key; } else { foreach(var alt in unitInfos[key].Alternates) { if (result.IsEmpty() && value.ToLower().Contains(alt.ToLower())) { result = key; } } } } } if (result.IsEmpty()) result = Stock; return result; } class LeadTimeUnitInfo { public string Name { get; set; } public string[] Alternates { get; set; } public TimeSpan TimeSpan { get; set; } } } }