using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Reflection;

namespace TwoCamWPF.Helpers
{


	class FileArchive
	{

        class FileInfoComparer : IComparer<FileInfo>
	    {
		    public int Compare(FileInfo x, FileInfo y)
		    {
			    return x.CreationTime.CompareTo(y.CreationTime);
		    }
	    }

		static FileInfo[] Get(string path)
		{
            Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), "  Получение списка видеофайлов ");
           
			DirectoryInfo dir = new DirectoryInfo(path);
			FileInfo[] files = dir.GetFiles("*.avi");

			Array.Sort<FileInfo>(files, new FileInfoComparer());
            Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), "  В папке  " + path + " находится " + files.Length + " видеофайлов");
           
			return files;
		}


        public static void DeleteOldFiles(string path,  int count)
		{

            Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), "  Удаление старых файлов");
           
            new Thread(() => {
			    FileInfo[] files = Get(path);
                if (files.Length < count)
                    return;
			    for (int index = 0; index <  files.Length - count+1; ++index)
			    {
				    try
				    {
					    File.Delete(files[index].FullName);
				    }
				    catch (Exception e){
                        Log.LogClass.Enqueue(MethodBase.GetCurrentMethod(), "Ошибка удаления " + e.Message);
                    }
			    }
            }) { Name = "DeleteOldFiles", Priority = ThreadPriority.Lowest  }.Start();
		}
	
	}


}
