// 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.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace WPFMA
{
    internal static class WPFMAChangeLog
    {
        internal const string Root = "WPFMA-Snapshots";
        private const string KeepKey = "WPFMA.ChangeLog.Keep";
        private const string EnabledKey = "WPFMA.ChangeLog.Enabled";

        [Serializable]
        internal sealed class Entry
        {
            public string id;
            public string tool;
            public string action;
            public string result;
            public string time;
            public string scenePath;
            public bool hasScene;
            public List<string> assets = new List<string>();
            public List<string> created = new List<string>();
            public bool reverted;
            public bool failed;
            public long bytes;

            [NonSerialized] public string Folder;
        }

        private static List<Entry> cache;

        /// <summary>Raised after an entry was put back (Team uses it to share a reverted scene).</summary>
        internal static event Action<Entry> Reverted;

        /// <summary>Saves a snapshot now and returns the entry, for changes that arrive over time (Team).</summary>
        internal static Entry Begin(string tool, string action, IEnumerable<string> assets, bool scene, string result)
        {
            if (!Enabled)
                return null;
            try
            {
                var entry = Snapshot(tool, action, assets, scene);
                entry.result = result;
                Save(entry);
                Prune();
                return entry;
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not save a snapshot before '" + action + "': " + e.Message);
                return null;
            }
        }

        /// <summary>Adds more files to an entry made with Begin, keeping the first copy of each.</summary>
        internal static void AddAssets(Entry entry, IEnumerable<string> assets, IEnumerable<string> created, string result)
        {
            if (entry == null || entry.reverted)
                return;
            try
            {
                if (entry.Folder == null)
                    entry.Folder = Path.Combine(Root, entry.id);
                foreach (var asset in (assets ?? Enumerable.Empty<string>()).Where(a => !string.IsNullOrEmpty(a)).Distinct())
                {
                    if (entry.assets.Contains(asset) || entry.created.Contains(asset) || !File.Exists(asset))
                        continue;
                    string slot = Path.Combine(entry.Folder, "asset" + entry.assets.Count);
                    File.Copy(asset, slot, true);
                    entry.bytes += new FileInfo(slot).Length;
                    if (File.Exists(asset + ".meta"))
                        File.Copy(asset + ".meta", slot + ".meta", true);
                    entry.assets.Add(asset);
                }
                foreach (var path in created ?? Enumerable.Empty<string>())
                    if (!string.IsNullOrEmpty(path) && !entry.created.Contains(path) && !entry.assets.Contains(path))
                        entry.created.Add(path);
                if (result != null)
                    entry.result = result;
                Save(entry);
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not add to the change log: " + e.Message);
            }
        }

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

        internal static int Keep
        {
            get { return Mathf.Clamp(EditorPrefs.GetInt(KeepKey, 30), 5, 200); }
            set { EditorPrefs.SetInt(KeepKey, Mathf.Clamp(value, 5, 200)); }
        }

        internal static string Run(string tool, string action, IEnumerable<string> assets, bool scene, Func<string> change)
        {
            return Run(tool, action, assets, scene, change, null);
        }

        internal static string Run(string tool, string action, IEnumerable<string> assets, bool scene, Func<string> change,
            Func<IEnumerable<string>> created)
        {
            Entry entry = null;
            if (Enabled)
            {
                try
                {
                    entry = Snapshot(tool, action, assets, scene);
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[WPFMA-SDK] Could not save a snapshot before '" + action + "': " + e.Message);
                }
            }

            string result;
            try
            {
                result = change();
            }
            catch (Exception e)
            {
                if (entry != null)
                {
                    entry.failed = true;
                    entry.result = "Failed: " + e.Message;
                    Save(entry);
                }
                throw;
            }

            if (entry != null)
            {
                entry.result = result;
                if (created != null)
                {
                    try
                    {
                        entry.created.AddRange((created() ?? Enumerable.Empty<string>()).Where(p => !string.IsNullOrEmpty(p)));
                    }
                    catch (Exception)
                    {
                    }
                }
                Save(entry);
                Prune();
            }

            return result;
        }

        private static Entry Snapshot(string tool, string action, IEnumerable<string> assets, bool scene)
        {
            string id = DateTime.Now.ToString("yyyyMMdd-HHmmss-fff");
            string folder = Path.Combine(Root, id);
            Directory.CreateDirectory(folder);

            var entry = new Entry
            {
                id = id,
                tool = tool,
                action = action,
                time = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
                Folder = folder
            };

            if (scene)
            {
                var active = EditorSceneManager.GetActiveScene();
                if (active.IsValid() && !string.IsNullOrEmpty(active.path))
                {
                    string copy = Path.Combine(folder, "scene.unity");
                    bool saved = false;

                    try
                    {
                        saved = EditorSceneManager.SaveScene(active, copy.Replace('\\', '/'), true) && File.Exists(copy);
                    }
                    catch (Exception)
                    {
                        saved = false;
                    }

                    if (!saved)
                    {
                        if (active.isDirty)
                            EditorSceneManager.SaveScene(active);
                        if (File.Exists(active.path))
                        {
                            File.Copy(active.path, copy, true);
                            saved = true;
                        }
                    }

                    if (saved)
                    {
                        entry.hasScene = true;
                        entry.scenePath = active.path;
                        entry.bytes += new FileInfo(copy).Length;
                    }
                }
            }

            if (assets != null)
            {
                AssetDatabase.SaveAssets();
                int index = 0;
                foreach (var asset in assets.Where(a => !string.IsNullOrEmpty(a)).Distinct())
                {
                    if (!File.Exists(asset))
                        continue;

                    string slot = Path.Combine(folder, "asset" + index);
                    File.Copy(asset, slot, true);
                    entry.bytes += new FileInfo(slot).Length;
                    if (File.Exists(asset + ".meta"))
                        File.Copy(asset + ".meta", slot + ".meta", true);

                    entry.assets.Add(asset);
                    index++;
                }
            }

            Save(entry);
            return entry;
        }

        private static void Save(Entry entry)
        {
            if (entry.Folder == null)
                entry.Folder = Path.Combine(Root, entry.id);
            Directory.CreateDirectory(entry.Folder);
            File.WriteAllText(Path.Combine(entry.Folder, "entry.json"), JsonUtility.ToJson(entry, true));
            cache = null;
        }

        internal static List<Entry> Entries()
        {
            if (cache != null)
                return cache;

            cache = new List<Entry>();
            if (!Directory.Exists(Root))
                return cache;

            foreach (var folder in Directory.GetDirectories(Root))
            {
                string json = Path.Combine(folder, "entry.json");
                if (!File.Exists(json))
                    continue;

                try
                {
                    var entry = JsonUtility.FromJson<Entry>(File.ReadAllText(json));
                    if (entry == null)
                        continue;
                    entry.Folder = folder;
                    cache.Add(entry);
                }
                catch (Exception)
                {
                }
            }

            cache = cache.OrderByDescending(e => e.id).ToList();
            return cache;
        }

        internal static int LaterSceneChanges(Entry entry)
        {
            if (!entry.hasScene)
                return 0;
            return Entries().Count(e => !e.reverted && string.CompareOrdinal(e.id, entry.id) > 0 && e.hasScene && e.scenePath == entry.scenePath);
        }

        internal static string Revert(Entry entry)
        {
            var restored = new List<string>();

            for (int i = 0; i < entry.assets.Count; i++)
            {
                string slot = Path.Combine(entry.Folder, "asset" + i);
                string target = entry.assets[i];
                if (!File.Exists(slot))
                    continue;

                Directory.CreateDirectory(Path.GetDirectoryName(target));
                File.Copy(slot, target, true);
                if (File.Exists(slot + ".meta"))
                    File.Copy(slot + ".meta", target + ".meta", true);
                restored.Add(target);
            }

            foreach (var path in restored)
                AssetDatabase.ImportAsset(path.EndsWith(".meta") ? path.Substring(0, path.Length - 5) : path, ImportAssetOptions.ForceUpdate);

            int deleted = 0;
            foreach (var path in entry.created)
            {
                if (path.StartsWith("Assets/") && (File.Exists(path) || Directory.Exists(path)) && AssetDatabase.DeleteAsset(path))
                    deleted++;
            }

            bool sceneRestored = false;
            if (entry.hasScene)
            {
                string copy = Path.Combine(entry.Folder, "scene.unity");
                if (File.Exists(copy) && !string.IsNullOrEmpty(entry.scenePath))
                {
                    File.Copy(copy, entry.scenePath, true);
                    AssetDatabase.ImportAsset(entry.scenePath, ImportAssetOptions.ForceUpdate);
                    EditorSceneManager.OpenScene(entry.scenePath, OpenSceneMode.Single);
                    sceneRestored = true;
                }
            }

            entry.reverted = true;
            Save(entry);
            AssetDatabase.Refresh();
            if (Reverted != null)
            {
                try
                {
                    Reverted(entry);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            }

            var parts = new List<string>();
            if (sceneRestored)
                parts.Add("the scene");
            if (restored.Count > 0)
                parts.Add(restored.Count + " file(s)");
            if (deleted > 0)
                parts.Add("removed " + deleted + " file(s) it had made");

            return parts.Count == 0 ? "Nothing to put back." : "Put back " + string.Join(", ", parts.ToArray()) + " from before '" + entry.action + "'.";
        }

        internal static void Delete(Entry entry)
        {
            try
            {
                Directory.Delete(entry.Folder, true);
            }
            catch (Exception)
            {
            }
            cache = null;
        }

        internal static void Prune()
        {
            var all = Entries();
            foreach (var old in all.Skip(Keep).ToList())
                Delete(old);
            cache = null;
        }

        internal static long TotalBytes()
        {
            return Entries().Sum(e => e.bytes);
        }

        internal static IEnumerable<string> MetaPaths(IEnumerable<string> assetPaths)
        {
            return assetPaths.Where(p => !string.IsNullOrEmpty(p) && p.StartsWith("Assets/")).Select(p => p + ".meta");
        }

        internal static string AssetPath(UnityEngine.Object asset)
        {
            return asset != null ? AssetDatabase.GetAssetPath(asset) : null;
        }

        internal static IEnumerable<string> AssetPaths(IEnumerable<UnityEngine.Object> assets)
        {
            return assets.Where(a => a != null).Select(AssetDatabase.GetAssetPath).Where(p => !string.IsNullOrEmpty(p) && p.StartsWith("Assets/"));
        }

        internal static string[] NewFiles(string folder, HashSet<string> before)
        {
            if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                return new string[0];
            return Directory.GetFiles(folder).Where(f => !f.EndsWith(".meta")).Select(f => f.Replace('\\', '/'))
                .Where(f => before == null || !before.Contains(f)).ToArray();
        }

        internal static HashSet<string> FilesIn(string folder)
        {
            if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                return new HashSet<string>();
            return new HashSet<string>(Directory.GetFiles(folder).Select(f => f.Replace('\\', '/')));
        }
    }

    internal static class WPFMAChangeLogSection
    {
        private const string PrefKey = "WPFMA.Tools.ChangeLogExpanded";

        private static string status;
        private static Vector2 scroll;

        internal static void Draw(GUIStyle sectionStyle)
        {
            int count = WPFMAChangeLog.Entries().Count(e => !e.reverted);
            WPFMAToolSection.Draw(sectionStyle, "Change log", count + " change(s) you can undo", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Every tool change, with Revert.", "Every change a WPFMA tool makes is listed here, newest first. Before each one, a copy of the scene and of the " + "files it touched was saved - Revert puts them back, even after Unity was closed."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            using (new EditorGUILayout.HorizontalScope())
            {
                bool enabled = EditorGUILayout.ToggleLeft("Save a copy before every change", WPFMAChangeLog.Enabled);
                if (enabled != WPFMAChangeLog.Enabled)
                    WPFMAChangeLog.Enabled = enabled;

                EditorGUILayout.LabelField("Keep the last", GUILayout.Width(85f));
                int keep = EditorGUILayout.IntField(WPFMAChangeLog.Keep, GUILayout.Width(40f));
                if (keep != WPFMAChangeLog.Keep)
                    WPFMAChangeLog.Keep = keep;
            }

            var entries = WPFMAChangeLog.Entries();
            EditorGUILayout.LabelField(entries.Count + " saved, using " + (WPFMAChangeLog.TotalBytes() / (1024.0 * 1024.0)).ToString("0.0") +
                                       " MB in the project's " + WPFMAChangeLog.Root + " folder (outside Assets, never uploaded).",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (entries.Count == 0)
            {
                EditorGUILayout.LabelField("No changes yet.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(360f));
            foreach (var entry in entries)
                DrawEntry(entry);
            EditorGUILayout.EndScrollView();

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Delete all saved copies", EditorStyles.miniButton, GUILayout.Width(160f)))
                {
                    EditorApplication.delayCall += () =>
                    {
                        if (!EditorUtility.DisplayDialog("Change log", "Delete every saved copy? You will not be able to revert these changes any more.", "Delete", "Cancel"))
                            return;
                        foreach (var entry in WPFMAChangeLog.Entries().ToList())
                            WPFMAChangeLog.Delete(entry);
                        status = "Deleted all saved copies.";
                    };
                }
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }

        private static void DrawEntry(WPFMAChangeLog.Entry entry)
        {
            EditorGUILayout.Space(3f);
            var rect = EditorGUILayout.BeginVertical();
            var color = entry.reverted ? WPFMAToolSection.FaintText : entry.failed ? WPFMAToolSection.WarnAmber : WPFMAToolSection.AccentBlue;
            EditorGUI.DrawRect(new Rect(rect.x, rect.y, 3f, rect.height), color);

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(8f);
                EditorGUILayout.LabelField(entry.tool + ": " + entry.action + (entry.reverted ? "  (reverted)" : string.Empty),
                    new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = color } });
                EditorGUILayout.LabelField(entry.time, WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(105f));
            }

            if (!string.IsNullOrEmpty(entry.result))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(8f);
                    EditorGUILayout.LabelField(entry.result, WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                }
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(8f);
                var saved = new List<string>();
                if (entry.hasScene)
                    saved.Add("scene '" + System.IO.Path.GetFileNameWithoutExtension(entry.scenePath) + "'");
                if (entry.assets.Count > 0)
                    saved.Add(entry.assets.Count + " file(s)");
                EditorGUILayout.LabelField(saved.Count == 0 ? "Nothing was saved for this one." : "Saved: " + string.Join(", ", saved.ToArray()),
                    WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

                using (new EditorGUI.DisabledScope(entry.reverted || saved.Count == 0))
                {
                    if (GUILayout.Button("Revert", EditorStyles.miniButtonLeft, GUILayout.Width(60f)))
                    {
                        var chosen = entry;
                        EditorApplication.delayCall += () => Revert(chosen);
                    }
                }

                if (GUILayout.Button("Forget", EditorStyles.miniButtonRight, GUILayout.Width(55f)))
                {
                    var chosen = entry;
                    EditorApplication.delayCall += () => WPFMAChangeLog.Delete(chosen);
                }
            }

            EditorGUILayout.EndVertical();
        }

        private static void Revert(WPFMAChangeLog.Entry entry)
        {
            var message = "Put things back to how they were before '" + entry.action + "' (" + entry.time + ")?";
            if (entry.hasScene)
            {
                message += "\n\nThe scene '" + System.IO.Path.GetFileNameWithoutExtension(entry.scenePath) + "' is reloaded from the saved copy, " +
                           "so anything done to it since then is lost";
                int later = WPFMAChangeLog.LaterSceneChanges(entry);
                message += later > 0 ? " - including " + later + " later change(s) in this log." : ".";
            }
            if (entry.assets.Count > 0)
                message += "\n\n" + entry.assets.Count + " file(s) go back to their saved versions.";
            if (entry.created.Count > 0)
                message += "\n\n" + entry.created.Count + " file(s) this change made are deleted.";

            if (!EditorUtility.DisplayDialog("Revert change", message, "Revert", "Cancel"))
                return;

            try
            {
                status = WPFMAChangeLog.Revert(entry);
            }
            catch (Exception e)
            {
                status = "Revert failed: " + e.Message;
                Debug.LogWarning("[WPFMA-SDK] Revert failed: " + e);
            }
        }
    }
}
#endif
