using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BodyshopPartner.Models;

namespace BodyshopPartner.Utils
{
    public class CIECAMonitor : FileSystemWatcher
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public CIECAMonitor()
        {
            Init();
        }

        public CIECAMonitor(String inDirectoryPath)
            : base(inDirectoryPath)
        {
            Init();
        }

        public CIECAMonitor(String inDirectoryPath, string inFilter)
            : base(inDirectoryPath, inFilter)
        {
            Init();
        }


        private void Init()
        {
            IncludeSubdirectories = false;
            // Eliminate duplicates when timestamp doesn't change
            Filter = "*.env";
            NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
            //NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; // The default also has NotifyFilters.LastWrite
            EnableRaisingEvents = true;
            Created += Watcher_Created;
            Changed += Watcher_Changed;
            //Deleted += Watcher_Deleted;
            //Renamed += Watcher_Renamed;
            Error += Wathcer_Error;
            logger.Debug("CIECA Folder watcher initialized for path: {0}", Path);
        }

        private void Wathcer_Error(object sender, ErrorEventArgs e)
        {
            logger.Error("CIECA monitor encountered an error. Trying to restart. {0}", e.ToString());
            ((FileSystemWatcher)sender).EnableRaisingEvents = true;
        }

        public void Watcher_Created(object source, FileSystemEventArgs inArgs)
        {
            logger.Trace("New CIECA fileset detected | {0}", inArgs.FullPath, inArgs.ChangeType);
            JobProcessingQueue.Enqueue(new DTO_QueueItem() { FilePath = inArgs.FullPath });
        }

        public void Watcher_Changed(object sender, FileSystemEventArgs inArgs)
        {
            logger.Trace("Updated CIECA fileset detected | {0}", inArgs.FullPath);
            JobProcessingQueue.Enqueue(new DTO_QueueItem() { FilePath = inArgs.FullPath });
        }
        public void Watcher_Deleted(object sender, FileSystemEventArgs inArgs)
        {
        }

        public void Watcher_Renamed(object sender, RenamedEventArgs inArgs)
        {
        }

        private void InitializeComponent()
        {
            ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
            // 
            // FolderMonitor
            // 
            this.IncludeSubdirectories = false;
            ((System.ComponentModel.ISupportInitialize)(this)).EndInit();

        }
    }
}
