using System.Collections.Generic;
using System.IO;
using System.Linq;
using Inspectron.Ringbuffer.Interfaces;

namespace Inspectron.Ringbuffer
{
    /// <summary>
    ///     Ringbuffer\Good\Product\File
    /// </summary>
    public class RootIndex : IIndex
    {
        private readonly List<string> _trackedGoodFiles = new List<string>();
        private readonly List<string> _trackedBadFiles = new List<string>();
        private readonly object _lock = new object();

        public void Track(string filePath)
        {
            lock (_lock)
            {
                if (IsGood(filePath))
                {
                    if (!_trackedGoodFiles.Contains(filePath))
                        _trackedGoodFiles.Insert(0, filePath);
                }
                else
                {
                    if (!_trackedBadFiles.Contains(filePath))
                        _trackedBadFiles.Insert(0, filePath);
                }
            }
        }


        public List<string> GetFilesToDelete(int allowedAmountGood, int allowedAmountBad)
        {
            lock (_lock)
            {
                var resGood = _trackedGoodFiles.Skip(allowedAmountGood).ToList();
                var resBad = _trackedBadFiles.Skip(allowedAmountBad).ToList();

                resGood.ForEach(x => { _trackedGoodFiles.Remove(x); });
                resBad.ForEach(x => { _trackedBadFiles.Remove(x); });

                return resGood.Concat(resBad).ToList();
            }
        }

        private bool IsGood(string filePath)
        {
            var folder = Path.GetDirectoryName(Path.GetDirectoryName(filePath)).Split(Path.DirectorySeparatorChar)
                .Last();
            return folder == RingbufferFolder.GOOD_DIR;
        }
    }
}