// 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.Linq;
using System.Security.Cryptography;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace WPFMA.Team
{
    /// <summary>
    /// The out-of-sync check. While nobody is editing, the host sends a fingerprint of each shared scene now and then
    /// (objects, names, on/off, components, the files they use, and where everything is). A guest whose copy differs
    /// asks the host for a per-object list, works out which objects drifted, and either fixes it straight away (a fresh
    /// copy of the scene from the host) or shows it in the Team tab with a Fix button. Guests report back, so the host
    /// sees who matches.
    /// </summary>
    internal static partial class TeamScene
    {
        private const string AutoFixKey = "WPFMA.Team.AutoFixDrift";

        /// <summary>Fix a drifted scene straight away (on), or show it with a Fix button (off).</summary>
        internal static bool AutoFix
        {
            get { return EditorPrefs.GetBool(AutoFixKey, true); }
            set { EditorPrefs.SetBool(AutoFixKey, value); }
        }

        /// <summary>The shared scene that drifted here (null when everything matches).</summary>
        internal static string DriftScene { get; private set; }

        /// <summary>Names of the objects that differ (at most a few), for the Team tab.</summary>
        internal static readonly List<string> DriftNames = new List<string>();

        internal static int DriftCount { get; private set; }

        /// <summary>A fresh copy was asked for and hasn't been checked yet.</summary>
        internal static bool Fixing { get; private set; }

        /// <summary>When this editor last compared (guest) or sent (host) a fingerprint.</summary>
        internal static double LastCheck { get; private set; } = -1;

        /// <summary>Host: each guest's last answer ("" = matches, else what differs).</summary>
        internal static readonly Dictionary<string, string> GuestCheck = new Dictionary<string, string>();

        /// <summary>Scene changes made here but not sent yet, or received but not applied yet.</summary>
        internal static int PendingCount
        {
            get { return dirty.Count + deferred.Count + held.Count; }
        }

        internal static string CheckNote { get; private set; }

        private static bool checkSoon;

        /// <summary>
        /// Play mode and animation previews (Animation window, Timeline) move things on one side for a while; the
        /// scene isn't really different, so it isn't checked then.
        /// </summary>
        private static bool Previewing
        {
            get { return EditorApplication.isPlayingOrWillChangePlaymode || AnimationMode.InAnimationMode(); }
        }
        private static double fixingSince;

        private static bool IsCheckOp(string mt)
        {
            return mt == "dig" || mt == "digq" || mt == "digl" || mt == "digr" || mt == "digs" || mt == "digb";
        }

        private static int Round(float value)
        {
            return (int)Math.Round(value * 1000.0);
        }

        /// <summary>One object as text: everything the fingerprint compares. Rounded so tiny float noise doesn't count.</summary>
        private static string ObjectLine(GameObject go)
        {
            var text = new StringBuilder();
            text.Append(IdFor(go)).Append('|').Append(go.name).Append('|').Append(go.activeSelf ? '1' : '0').Append('|');
            var t = go.transform;
            var p = t.localPosition;
            var r = t.localRotation;
            var s = t.localScale;
            text.Append(Round(p.x)).Append(',').Append(Round(p.y)).Append(',').Append(Round(p.z)).Append(';')
                .Append(Round(r.x)).Append(',').Append(Round(r.y)).Append(',').Append(Round(r.z)).Append(',').Append(Round(r.w)).Append(';')
                .Append(Round(s.x)).Append(',').Append(Round(s.y)).Append(',').Append(Round(s.z)).Append('|');
            foreach (var component in go.GetComponents<Component>())
            {
                if (component == null || !Syncable(component))
                    continue;
                text.Append(component.GetType().Name).Append(',');
                AppendAssets(text, component);
            }
            return text.ToString();
        }

        // Each object's line, kept until something about it changes (building every line every check was slow in big scenes).
        private sealed class CachedLine
        {
            public long Key;
            public string Line;
        }

        private static readonly Dictionary<int, CachedLine> lineCache = new Dictionary<int, CachedLine>();
        private static readonly List<Component> lineComponents = new List<Component>();
        private static double lineCacheSince;

        private static string Line(GameObject go)
        {
            // Changes that don't mark anything dirty (a script setting a material) are picked up within a minute.
            if (TeamSession.Now - lineCacheSince > 60.0)
            {
                lineCache.Clear();
                lineCacheSince = TeamSession.Now;
            }
            long key = LineKey(go);
            CachedLine cached;
            if (lineCache.TryGetValue(go.GetInstanceID(), out cached) && cached.Key == key)
                return cached.Line;
            string line = ObjectLine(go);
            lineCache[go.GetInstanceID()] = new CachedLine { Key = key, Line = line };
            return line;
        }

        private static long LineKey(GameObject go)
        {
            unchecked
            {
                long h = 17;
                h = h * 31 + EditorUtility.GetDirtyCount(go.GetInstanceID());
                h = h * 31 + go.name.GetHashCode();
                h = h * 31 + IdFor(go).GetHashCode();
                h = h * 31 + (go.activeSelf ? 1 : 0);
                var t = go.transform;
                var p = t.localPosition;
                var r = t.localRotation;
                var s = t.localScale;
                h = h * 31 + Round(p.x); h = h * 31 + Round(p.y); h = h * 31 + Round(p.z);
                h = h * 31 + Round(r.x); h = h * 31 + Round(r.y); h = h * 31 + Round(r.z); h = h * 31 + Round(r.w);
                h = h * 31 + Round(s.x); h = h * 31 + Round(s.y); h = h * 31 + Round(s.z);
                go.GetComponents(lineComponents);
                foreach (var component in lineComponents)
                {
                    if (component == null)
                    {
                        h = h * 31 + 1;
                        continue;
                    }
                    h = h * 31 + component.GetInstanceID();
                    h = h * 31 + EditorUtility.GetDirtyCount(component.GetInstanceID());
                }
                lineComponents.Clear();
                return h;
            }
        }

        private static string Hash(string text)
        {
            using (var md5 = MD5.Create())
                return BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);
        }

        private static string Digest(Scene scene)
        {
            var text = new StringBuilder();
            foreach (var go in Walk(scene))
                text.Append(Line(go)).Append('\n');
            return Hash(text.ToString());
        }

        /// <summary>id \t short hash \t name, one object per line.</summary>
        private static string ObjectList(Scene scene)
        {
            var text = new StringBuilder();
            foreach (var go in Walk(scene))
                text.Append(IdFor(go)).Append('\t').Append(Hash(Line(go)).Substring(0, 10)).Append('\t').Append(go.name.Replace('\t', ' ').Replace('\n', ' ')).Append('\n');
            return text.ToString();
        }

        // ---- Checking ---------------------------------------------------------------------------------------------

        /// <summary>Check now instead of waiting for the next regular check.</summary>
        internal static void CheckNow()
        {
            if (!TeamSession.IsLinked)
                return;
            CheckNote = "Checking...";
            if (TeamSession.IsHost)
                checkSoon = true;
            else
                Direct(new TeamMessage { t = "op", mt = "digq" });
            TeamSession.Raise();
        }

        /// <summary>Gets a fresh copy of the drifted scene from the host.</summary>
        internal static void FixNow()
        {
            if (DriftScene == null || TeamSession.IsHost)
                return;
            Fixing = true;
            fixingSince = TeamSession.Now;
            RequestScene(DriftScene);
            TeamSession.Raise();
        }

        private static void SendDigests()
        {
            if (!TeamSession.IsHost || (!checkSoon && TeamSession.Now - lastDigest < DigestInterval))
                return;
            if (!Quiet || Previewing)
            {
                if (checkSoon)
                    CheckNote = "Waiting for edits to settle, then checking...";
                return;
            }
            checkSoon = false;
            lastDigest = TeamSession.Now;
            LastCheck = TeamSession.Now;
            CheckNote = null;
            foreach (var path in live)
            {
                var scene = SceneManager.GetSceneByPath(path);
                if (scene.IsValid() && scene.isLoaded)
                    Direct(new TeamMessage { t = "op", mt = "dig", f = path, h = Digest(scene) });
            }
        }

        private static void CheckDigest(TeamMessage message)
        {
            var scene = SceneManager.GetSceneByPath(message.f);
            if (!scene.IsValid() || !scene.isLoaded || !live.Contains(message.f) || TeamSession.IsHost || TeamFiles.Receiving)
                return;
            if (TeamSession.Now - lastActivity < 3.0 && dirty.Count > 0)
                return;
            if (Previewing)
                return;

            LastCheck = TeamSession.Now;
            CheckNote = null;
            bool forced = message.o;
            if (Digest(scene) == message.h)
            {
                digestMisses = 0;
                bool was = DriftScene != null;
                ClearDrift();
                Report(message.f, 0);
                if (was)
                    TeamSession.AddSystem(scene.name + " matches " + TeamSession.RemoteName + "'s again.");
                TeamSession.Raise();
                return;
            }

            // One miss can be a change still on its way; ask for the details after two (or straight away when asked).
            if (!forced && ++digestMisses < 2)
                return;
            digestMisses = 0;
            Direct(new TeamMessage { t = "op", mt = "digl", f = message.f });
        }

        /// <summary>Guest: which objects differ, from the host's per-object list.</summary>
        private static void CompareObjects(TeamMessage message)
        {
            var scene = SceneManager.GetSceneByPath(message.f);
            if (TeamSession.IsHost || !scene.IsValid() || !scene.isLoaded || !live.Contains(message.f) || Previewing)
                return;

            var theirs = new Dictionary<string, KeyValuePair<string, string>>();
            foreach (var line in (message.json ?? string.Empty).Split('\n'))
            {
                var parts = line.Split('\t');
                if (parts.Length >= 3)
                    theirs[parts[0]] = new KeyValuePair<string, string>(parts[1], parts[2]);
            }

            var names = new List<string>();
            int count = 0;
            var seen = new HashSet<string>();
            foreach (var go in Walk(scene))
            {
                string id = IdFor(go);
                seen.Add(id);
                KeyValuePair<string, string> other;
                if (!theirs.TryGetValue(id, out other))
                {
                    count++;
                    if (names.Count < 5)
                        names.Add(go.name + " (only here)");
                }
                else if (other.Key != Hash(Line(go)).Substring(0, 10))
                {
                    count++;
                    if (names.Count < 5)
                        names.Add(go.name);
                }
            }
            foreach (var pair in theirs.Where(p => !seen.Contains(p.Key)))
            {
                count++;
                if (names.Count < 5)
                    names.Add(pair.Value.Value + " (missing here)");
            }
            if (count == 0)
            {
                // Same objects, different order in the Hierarchy.
                count = 1;
                names.Add("the order of objects in the Hierarchy");
            }

            bool news = DriftScene != message.f || DriftCount != count;
            DriftScene = message.f;
            DriftCount = count;
            DriftNames.Clear();
            DriftNames.AddRange(names);
            Report(message.f, count);

            string list = string.Join(", ", names.ToArray()) + (count > names.Count ? " and " + (count - names.Count) + " more" : string.Empty);
            if (!news && (Fixing || !AutoFix))
            {
                // Same drift as last time: already being fixed, or already shown.
                if (Fixing && TeamSession.Now - fixingSince > 60.0)
                    FixNow();
                TeamSession.Raise();
                return;
            }
            if (AutoFix)
            {
                TeamSession.AddSystem(scene.name + " drifted out of sync (" + list + "). Getting a fresh copy from " + TeamSession.RemoteName + ".");
                FixNow();
            }
            else
            {
                TeamSession.AddSystem(scene.name + " is out of sync (" + list + "). Press Fix in the Team tab to get a fresh copy.");
            }
            TeamSession.Raise();
        }

        private static void Report(string path, int differ)
        {
            Direct(new TeamMessage { t = "op", mt = "digs", f = path, n = differ, m = string.Join(", ", DriftNames.ToArray()) });
        }

        private static void ClearDrift()
        {
            DriftScene = null;
            DriftCount = 0;
            DriftNames.Clear();
            Fixing = false;
        }

        /// <summary>The check ops: questions to the host, the host's answers, and guests' reports.</summary>
        private static void ApplyCheckOp(TeamMessage message)
        {
            var sender = TeamSession.Sender;
            switch (message.mt)
            {
                case "dig":
                    CheckDigest(message);
                    return;

                case "digq":
                    // A guest pressed Check now: answer that guest only, once nobody is mid-edit.
                    if (!TeamSession.IsHost)
                        return;
                    if (!Quiet || Previewing)
                    {
                        Reply(new TeamMessage { t = "op", mt = "digb" });
                        return;
                    }
                    foreach (var path in live)
                    {
                        var scene = SceneManager.GetSceneByPath(path);
                        if (scene.IsValid() && scene.isLoaded)
                            Reply(new TeamMessage { t = "op", mt = "dig", f = path, h = Digest(scene), o = true });
                    }
                    return;

                case "digb":
                    if (!TeamSession.IsHost)
                    {
                        CheckNote = "Someone is still editing; the regular check runs once it settles.";
                        TeamSession.Raise();
                    }
                    return;

                case "digl":
                    if (TeamSession.IsHost)
                    {
                        var scene = SceneManager.GetSceneByPath(message.f);
                        if (scene.IsValid() && scene.isLoaded)
                            Reply(new TeamMessage { t = "op", mt = "digr", f = message.f, json = ObjectList(scene) });
                    }
                    return;

                case "digr":
                    CompareObjects(message);
                    return;

                case "digs":
                    if (TeamSession.IsHost && sender != null)
                    {
                        GuestCheck[sender.Id] = message.n == 0 ? string.Empty :
                            message.n + " object" + (message.n == 1 ? string.Empty : "s") + " differ" + (message.n == 1 ? "s" : string.Empty) +
                            (string.IsNullOrEmpty(message.m) ? string.Empty : " (" + message.m + ")");
                        LastCheck = TeamSession.Now;
                        TeamSession.Raise();
                    }
                    return;
            }
        }
    }
}
#endif
