using System; using System.Collections.Generic; using System.IO; using System.Linq; using Inspectron.Ringbuffer.Interfaces; namespace Inspectron.Ringbuffer { public class GroupIndex:IIndex { private readonly int _groupPathPart; private readonly int _goodBadPathPart; public GroupIndex(int groupPathPart,int goodBadPathPart) { _groupPathPart = groupPathPart; _goodBadPathPart = goodBadPathPart; } private readonly object _lock = new object(); private readonly Dictionary _groups = new Dictionary(); public void Track(string filePath) { var parts = Path.GetDirectoryName(filePath).Split(Path.DirectorySeparatorChar); string groupKey; try { groupKey = Path.Combine(Enumerable.Range(0, _groupPathPart + 1).Select(x => parts[x]).ToArray()); } catch (Exception e) { Console.WriteLine($"Tracking {filePath}"); Console.WriteLine(e); return; } string badGoodPart; if (_goodBadPathPart == -1) badGoodPart = RingbufferPath.GOOD_DIR; else badGoodPart = parts[_goodBadPathPart]; lock (_lock) { if (!_groups.ContainsKey(groupKey)) { _groups[groupKey] = new ProductResults(); } if (badGoodPart == RingbufferPath.GOOD_DIR) { _groups[groupKey].Good.Insert(0,filePath); } else { _groups[groupKey].Bad.Insert(0, filePath); } } } public List GetFilesToDelete(int allowedAmountGood, int allowedAmountBad) { lock (_lock) { var filesToDelete = new List(); foreach (var p in _groups) { var goodToDelete = p.Value.Good.Skip(allowedAmountGood).ToList(); var badToDelete = p.Value.Bad.Skip(allowedAmountBad).ToList(); goodToDelete.ForEach(x => p.Value.Good.Remove(x)); badToDelete.ForEach(x => p.Value.Bad.Remove(x)); filesToDelete.AddRange(goodToDelete); filesToDelete.AddRange(badToDelete); } return filesToDelete; } } private class ProductResults { public List Good { get; set; }=new List(); public List Bad { get; set; }=new List(); } } }