using Aitex.Core.RT.Log;
using System;
using System.Collections.Generic;
using System.IO;

namespace Aitex.Core.Util
{
    /// <summary>
    /// 文件变更监视器管理器。
    /// </summary>
    public class FileSystemWatcherManager : Singleton<FileSystemWatcherManager>
    {
        #region Variables

        private readonly Dictionary<FileSystemWatcher, Action<string>> _dicWatches = new();

        #endregion

        #region Properties

        /// <summary>
        /// 返回注册的文件监视器的总数。
        /// </summary>
        public int Count => _dicWatches.Count;  

        #endregion

        #region Methods

        /// <summary>
        /// 注册一个监视器用于监视指定文件内容的变更。
        /// </summary>
        /// <param name="fullFileName">包含完整路径的文件名。</param>
        /// <param name="CallbackOnFileChanged">当文件内容发生变化时执行的回调函数。</param>
        public virtual void Register(string fullFileName, Action<string> CallbackOnFileChanged)
        {
            if(File.Exists(fullFileName))
            {
                var path = Path.GetDirectoryName(fullFileName);
                var fn = Path.GetFileName(fullFileName);
                var watcher = new FileSystemWatcher(path, fn);
                watcher.Changed += OnChanged;
                watcher.IncludeSubdirectories = false;
                watcher.EnableRaisingEvents = true;

                _dicWatches.Add(watcher, CallbackOnFileChanged);

                LOG.Info($"New file watcher added for {fullFileName}");
            }
            else
            {
                LOG.Error($"Error to add file watcher for {fullFileName}, file not exists");
            }
           
        }


        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (sender is FileSystemWatcher watcher)
            {
                LOG.Info($"{e.FullPath} changes detected.");
                if(_dicWatches.TryGetValue(watcher, out var action))
                    action(e.FullPath);
            }
        }

        #endregion
    }
}
