/*
<copyright file="BGEditorEMFileWatcher.cs" company="BansheeGz">
    Copyright (c) 2019-2024 All Rights Reserved
</copyright>
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEngine;

namespace BansheeGz.BGDatabase.Editor
{
    public class BGEditorEMFileWatcher : IDisposable
    {
        private const long Interval = 1000;
        private static List<BGEditorEMFileWatcher> watchersList = new List<BGEditorEMFileWatcher>();
        private static readonly Timer Timer = new Timer(Poll, null, Interval, Timeout.Infinite);
        private static readonly object watchersLock = new object(); 

        private readonly string file; 
        private readonly Action action;
        private DateTime changed;

        private static void Poll(object state)
        {
            try
            {
                lock (watchersLock)
                {
                    foreach (var watcher in watchersList)
                    {
                        var lastWriteTime = File.GetLastWriteTime(watcher.file);
                        if (lastWriteTime <= watcher.changed) continue;
                        watcher.changed = lastWriteTime;
                        watcher.action();
                    }
                }
            }
            catch(Exception e)
            {
                Debug.LogException(e);
            }
            Timer.Change( Interval, Timeout.Infinite );
        }

        public BGEditorEMFileWatcher(string filePath, Action action)
        {
            this.file = filePath;
            this.action = action;
            changed = File.GetLastWriteTime(file); 
            lock (watchersLock) watchersList.Add(this);
        }

        public void Dispose()
        {
            lock (watchersLock) watchersList.Remove(this);
        }
    }
}

/*
 //FileSystemWatcher is unreliable (Macos + MO + xlsx not working)
private FileSystemWatcher fileSystemWatcher;
private readonly string filePath;
private readonly FileSystemEventHandler action;

public BGEditorEMFileWatcher(string filePath, FileSystemEventHandler action)
{
    this.filePath = filePath;
    this.action = action;
    fileSystemWatcher = new FileSystemWatcher();
    var directoryName = Path.GetDirectoryName(filePath);
    var fileName = Path.GetFileName(filePath);
    fileSystemWatcher = new FileSystemWatcher(directoryName)
    {
        Filter = fileName,
        NotifyFilter = NotifyFilters.LastWrite,
    };
    fileSystemWatcher.Changed += action;
    fileSystemWatcher.EnableRaisingEvents = true;
}

public void Dispose()
{
    if (fileSystemWatcher == null) return;
    fileSystemWatcher.Changed -= action;
    fileSystemWatcher.EnableRaisingEvents = false;
    fileSystemWatcher = null;
}
*/