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<string, ProductResults> _groups = new Dictionary<string, ProductResults>();

      
        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<string> GetFilesToDelete(int allowedAmountGood, int allowedAmountBad)
        {
            lock (_lock)
            {
                var filesToDelete = new List<string>();
                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<string> Good { get; set; }=new List<string>();
            public List<string> Bad { get; set; }=new List<string>();
        }
    }
}