// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.IO;
using System.Threading;
using UnityEditor;
using UnityEditorInternal;

namespace WPFMA
{
    /// <summary>
    /// Unity only looks for changed files when its window gets focus, so a script saved in another program (your code
    /// editor, a download, a tool) does nothing until you click into Unity. This watches Assets and Packages and, while
    /// Unity is in the background, refreshes (and so recompiles) a moment after something changes. While Unity is
    /// focused it does nothing - Unity handles that itself.
    /// </summary>
    [InitializeOnLoad]
    internal static class WPFMABackgroundRefresh
    {
        private const string EnabledKey = "WPFMA.BackgroundRefresh";

        // Wait this long after the last change, so a save of many files is one refresh.
        private const double Settle = 0.8;

        private static FileSystemWatcher[] watchers = new FileSystemWatcher[0];
        private static long lastChangeTicks;

        static WPFMABackgroundRefresh()
        {
            Start();
            EditorApplication.update += Tick;
            AssemblyReloadEvents.beforeAssemblyReload += Stop;
            EditorApplication.quitting += Stop;
        }

        internal static bool Enabled
        {
            get { return EditorPrefs.GetBool(EnabledKey, true); }
            set
            {
                EditorPrefs.SetBool(EnabledKey, value);
                Stop();
                Start();
            }
        }

        // Unity's own Preferences > Asset Pipeline > Auto Refresh (0 = off). When that's off, so is this.
        private static bool UnityAutoRefresh
        {
            get { return EditorPrefs.GetInt("kAutoRefreshMode", EditorPrefs.GetBool("kAutoRefresh", true) ? 1 : 0) != 0; }
        }

        private static void Start()
        {
            if (!Enabled || watchers.Length > 0)
                return;
            var list = new System.Collections.Generic.List<FileSystemWatcher>();
            foreach (var folder in new[] { "Assets", "Packages" })
            {
                try
                {
                    var watcher = new FileSystemWatcher(Path.GetFullPath(folder))
                    {
                        IncludeSubdirectories = true,
                        NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite | NotifyFilters.Size
                    };
                    watcher.Changed += OnChange;
                    watcher.Created += OnChange;
                    watcher.Deleted += OnChange;
                    watcher.Renamed += (sender, e) => OnChange(sender, e);
                    watcher.EnableRaisingEvents = true;
                    list.Add(watcher);
                }
                catch (Exception)
                {
                    // A folder we can't watch just means clicking into Unity, as before.
                }
            }
            watchers = list.ToArray();
        }

        private static void Stop()
        {
            foreach (var watcher in watchers)
            {
                try
                {
                    watcher.EnableRaisingEvents = false;
                    watcher.Dispose();
                }
                catch (Exception)
                {
                }
            }
            watchers = new FileSystemWatcher[0];
        }

        // Runs on a background thread: only note the time.
        private static void OnChange(object sender, FileSystemEventArgs e)
        {
            string path = e.FullPath ?? string.Empty;
            // Folders Unity never imports (name~, .hidden) and temporary files don't need a refresh.
            if (path.Contains("~" + Path.DirectorySeparatorChar) || path.EndsWith("~") || path.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase) ||
                path.Contains(Path.DirectorySeparatorChar + "."))
                return;
            Interlocked.Exchange(ref lastChangeTicks, DateTime.UtcNow.Ticks);
        }

        private static void Tick()
        {
            long ticks = Interlocked.Read(ref lastChangeTicks);
            if (ticks == 0)
                return;

            // Focused: Unity refreshes by itself.
            if (InternalEditorUtility.isApplicationActive || !UnityAutoRefresh)
            {
                Interlocked.CompareExchange(ref lastChangeTicks, 0, ticks);
                return;
            }
            if (EditorApplication.isCompiling || EditorApplication.isUpdating || EditorApplication.isPlayingOrWillChangePlaymode)
                return;
            if ((DateTime.UtcNow - new DateTime(ticks, DateTimeKind.Utc)).TotalSeconds < Settle)
                return;

            // Anything that changes during the refresh itself (like new .meta files) is picked up by the next one.
            Interlocked.CompareExchange(ref lastChangeTicks, 0, ticks);
            AssetDatabase.Refresh();
        }
    }
}
#endif
