using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ZionFoundation.GlobalTasks
{
    public class FolderMonitoring : Threading.Thread
    {
        #region Private properties
        private string path;
        private FileSystemEventHandler handler;
        private List<FileInfo> files;
        private List<DirectoryInfo> directories;

        #endregion

        #region Private functions
        private List<FileInfo> CurrentFilesInContent(string path)
        {
            if (!System.IO.Directory.Exists(path))
                return null;
            string[] current = Directory.GetFiles(path);
            List<FileInfo> list = new List<FileInfo>();
            current.ToList().ForEach(x =>
            {
                list.Add(new FileInfo(x));
            });
            return list;
        }
        private List<DirectoryInfo> CurrentDirectoriesInContent(string path)
        {
            string[] current = Directory.GetDirectories(path);
            List<DirectoryInfo> list = new List<DirectoryInfo>();
            current.ToList().ForEach(x =>
            {
                list.Add(new DirectoryInfo(x));
            });
            return list;
        }
        #endregion

        #region Overrides
        public override void Execute()
        {
            var files = CurrentFilesInContent(path);

            files?.ForEach(x =>
            {
                if (this.files?.Where(y => x.Name == y.Name
                    && x.Extension == y.Extension
                    && x.CreationTime == y.CreationTime
                    && x.LastWriteTime == y.LastWriteTime
                ).Count() == 0)
                    handler(this, new FileSystemEventArgs(WatcherChangeTypes.Changed, this.path, x.Name));
            });
            this.files = files;

            var directories = CurrentDirectoriesInContent(path);
            directories?.ForEach(x =>
            {
                if (this.directories?.Where(y => x.Name == y.Name).Count() == 0)
                {
                    handler(this, new FileSystemEventArgs(WatcherChangeTypes.Changed, this.path, x.Name));
                }
            });
            this.directories = directories;
        }
        #endregion

        #region Constructors
        public FolderMonitoring(string path, FileSystemEventHandler handler)
        {
            this.path = path;
            this.handler = handler;
        }
        #endregion
    }
}
