using ServiceStack.Messaging;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using Txgy.RBS.Framework.Models;

namespace Txgy.RBS.Framework.FileWatcherHelper
{
    public class FilesWatcherService
    {
        public FilesWatcherService(int proId, string projectName, string path)
        {
            projectId = proId;
            proName = projectName;
            watcherPath = path;
           // string filter = "*.txt";
           // WatcherPath = AppDomain.CurrentDomain.BaseDirectory;
           // InitializeParams(filter, watcherPath);      
        }
        private string watcherPath;

        public string WatcherPath
        {
            get { return watcherPath; }
        }
        private string proName;

        public string ProName
        {
            get { return proName; }
        }
        private int projectId;

        public int ProjectId
        {
            get { return projectId; }
        }

        public DateTime StartTime { get; set; }

        public void Start()
        {
            WatchStartOrSopt(true);
            StartTime = DateTime.Now;
        }

        public void Stop()
        {
            WatchStartOrSopt(false);

        }
        public Action<MsEventModel, FileSystemEventArgs> WatcherFileChanged;
        public void InitializeParams(string fileFilter="*.index")
        {

            //如果设置的目录不存在设置到根目录
            if (!File.Exists(watcherPath))
            {
                Directory.CreateDirectory(watcherPath);
              //  watcherPath = AppDomain.CurrentDomain.BaseDirectory;
            }
            watcher = new FileSystemWatcher();
            //初始化监听
            watcher.BeginInit();

            //设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
            watcher.NotifyFilter = NotifyFilters.Attributes
                                 | NotifyFilters.CreationTime
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.FileName
                                 | NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.Security
                                 | NotifyFilters.Size;
            //设置监听的路径
            watcher.Path = watcherPath;
            watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
            // watcher.Created += Watcher_Created;
            watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
            watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
            watcher.Error += OnError;

            //设置监听文件类型
            watcher.Filter = fileFilter;
            //设置是否监听子目录
            watcher.IncludeSubdirectories = true;
            //设置是否启用监听
            watcher.EnableRaisingEvents = false;
            watcher.EndInit();

        }

        private void OnError(object sender, ErrorEventArgs e)
        {

        }
        private void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Thread.Sleep(100);
            // string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
            DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
            watcher.EnableRaisingEvents = false;
            Debug.WriteLine($"最后修改时间：{lastWriteTime}");
            string lastLine = File.ReadLines(e.FullPath).Last().Trim();
            var msEvent = new MsEventModel(lastLine) { CurrentTime = DateTime.Now };
            msEvent.ProjectId = this.ProjectId;
            msEvent.ProjectName = this.ProName;
            WatcherFileChanged?.Invoke(msEvent, e);
            watcher.EnableRaisingEvents = true;
        }

        private void Watcher_Renamed(object sender, RenamedEventArgs e)
        {

            DateTime dt = DateTime.Now;
            string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
            tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
            tmp += "文件全称:" + e.FullPath + "\r\n";
        }

        private void Watcher_Created(object sender, FileSystemEventArgs e)
        {
            DateTime dt = DateTime.Now;
            string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
            tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
            tmp += "文件全称:" + e.FullPath + "\r\n";
        }

        private void Watcher_Deleted(object sender, FileSystemEventArgs e)
        {

            DateTime dt = DateTime.Now;
            string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
            tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
            tmp += "文件全称:" + e.FullPath + "\r\n";

        }

        /// <summary>
        /// 启动或者停止监听
        /// </summary>
        /// <param name="IsEnableRaising">True:启用监听,False:关闭监听</param>
        private void WatchStartOrSopt(bool IsEnableRaising)
        {
            watcher.EnableRaisingEvents = IsEnableRaising;
        }

        private FileSystemWatcher watcher = new FileSystemWatcher();
    }
}
