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

namespace Inspectron.Ringbuffer
{
    [Obsolete]
    public class RingbufferFolder:IFolderWritter
    {
        
        private string _ringbufferFolder;
        private RingbufferConfiguration _configuration;
        private IFileVerifier _fileVerifier;

        private IIndex _index;
        
        public RingbufferFolder(string ringbufferFolder, RingbufferConfiguration configuration, IFileVerifier fileVerifier)
        {
            _ringbufferFolder = ringbufferFolder;
            _configuration = configuration;
            _fileVerifier = fileVerifier;
            EnsureDirectory(_ringbufferFolder);
            InitIndex();


            var th1 = new Thread(RemoveLoop);
            th1.Priority = ThreadPriority.Normal;
            th1.Start();

            var th2 = new Thread(SaveLoop);
            th2.Priority = ThreadPriority.Normal;
            th2.Start();
        }

        private void RemoveLoop()
        {
            while (true)
            {
                var filesToDelete=_index.GetFilesToDelete(_configuration.MaxAmountOfGoodImages, _configuration.MaxAmountOfBadImages);
                
                filesToDelete.ForEach(x=>
                {
                    DeleteFile(x);
                    _fileVerifier.LinkedFiles(x).ForEach(DeleteFile);
                });

                Thread.Sleep(1000);
            }
        }

        ConcurrentQueue<SaveCandidate> _saveQueue = new ConcurrentQueue<SaveCandidate>();


        object _lock=new object();

        private void EnsureDirectory(string directory)
        {
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
        }
        private void SaveLoop()
        {
            while (true)
            {
                if (_saveQueue.TryDequeue(out var candidate))
                {
                    lock (_lock)
                    {
                        EnsureDirectory(candidate.TargetDirectory);
                        var written=candidate.FileIdentity.WriteTo(candidate.TargetDirectory);
                        _index.Track(written);
                    }
                }
                else
                {
                    Thread.Sleep(1);
                }
            }
        }

       

        private void InitIndex()
        {
            if (_configuration.ProductFirst)
            {
                _index=new ProductIndex();
            }
            else
            {
                _index=new RootIndex();
            }
            IndexFiles();
        }

        public void DeleteFile(string fileToDelete)
        {
            var fi = new System.IO.FileInfo(fileToDelete);
            if (fi.Exists)
            {
                lock (_lock)
                {
                    fi.Delete();
                }

                fi.Refresh();
                while (fi.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    fi.Refresh();
                }
            }
        }

        private void IndexFiles()
        {
            var allFiles=Directory.GetFiles(_ringbufferFolder, "*.*", SearchOption.AllDirectories);
            var verifiedFiles = allFiles.Where(x => _fileVerifier.IsMainFile(x)).ToList();
            var orderedFiles = verifiedFiles.OrderByDescending(x => new FileInfo(x).CreationTimeUtc).ToList();
            orderedFiles.ForEach(_index.Track);
        }

        public const string GOOD_DIR = "Good";
        public const string BAD_DIR = "Bad";
        public void WriteGood(IFileIdentity fileIdentity,string product)
        {
            var path = _configuration.ProductFirst
                ? Path.Combine(_ringbufferFolder, product, GOOD_DIR)
                : Path.Combine(_ringbufferFolder, GOOD_DIR, product);


                _saveQueue.Enqueue(new SaveCandidate(fileIdentity, path));
        }

        public void WriteBad(IFileIdentity fileIdentity, string product)
        {
            var path = _configuration.ProductFirst
                ? Path.Combine(_ringbufferFolder, product, BAD_DIR)
                : Path.Combine(_ringbufferFolder, BAD_DIR, product);

            _saveQueue.Enqueue(new SaveCandidate(fileIdentity, path));
        }
    }
}