// 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.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace WPFMA.Team
{
    /// <summary>
    /// Materials whose shader is not in this project (usually a paid shader the teammate owns) show pink. While in a
    /// session they are shown with a plain stand-in shader using the same main texture and color instead. This only
    /// changes the material in memory: saving it is blocked, and it is reloaded from disk when the session ends, the
    /// real shader gets installed, or the option is turned off. The file and the teammate's project are never touched.
    /// </summary>
    [InitializeOnLoad]
    internal static class TeamStandIns
    {
        private const string EnabledKey = "WPFMA.Team.StandIns";
        private const string SavedKey = "WPFMA.Team.StandInPaths";

        private static readonly Regex ShaderGuid = new Regex(@"m_Shader:\s*\{fileID:\s*-?\d+,\s*guid:\s*([0-9a-f]{32})", RegexOptions.Compiled);
        private static readonly Regex ShaderLine = new Regex(@"^  m_Shader:.*$", RegexOptions.Compiled | RegexOptions.Multiline);
        private static readonly Regex MainTex = new Regex(@"- _MainTex:\s*\r?\n\s*m_Texture:\s*\{fileID:\s*-?\d+(?:,\s*guid:\s*([0-9a-f]{32}))?", RegexOptions.Compiled);
        private static readonly Regex MainColor = new Regex(@"- _Color:\s*\{r:\s*([-\d.eE]+),\s*g:\s*([-\d.eE]+),\s*b:\s*([-\d.eE]+),\s*a:\s*([-\d.eE]+)\}", RegexOptions.Compiled);

        private static readonly HashSet<string> paths = new HashSet<string>();

        /// <summary>Path -> the material's real m_Shader line, kept across restarts so a leaked stand-in can be repaired.</summary>
        private static readonly Dictionary<string, string> originals = new Dictionary<string, string>();
        private static double lastScan = -100;

        static TeamStandIns()
        {
            string saved = SessionState.GetString(SavedKey, string.Empty);
            foreach (var path in saved.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                paths.Add(path);

            LoadOriginals();
            RepairFiles();
            EditorApplication.update += Update;
            EditorApplication.wantsToQuit += () =>
            {
                RestoreAll();
                return true;
            };
            TeamSession.Ended += RestoreAll;
            TeamSession.Suspending += Save;
            EditorSceneManager.sceneOpened += (scene, mode) => lastScan = -100;
        }

        internal static bool Enabled
        {
            get { return EditorPrefs.GetBool(EnabledKey, true); }
            set
            {
                EditorPrefs.SetBool(EnabledKey, value);
                if (!value)
                    RestoreAll();
                lastScan = -100;
            }
        }

        internal static int Count
        {
            get { return paths.Count; }
        }

        internal static bool IsStandIn(UnityEngine.Object asset)
        {
            if (paths.Count == 0 || !(asset is Material))
                return false;
            return paths.Contains(AssetDatabase.GetAssetPath(asset));
        }

        internal static bool IsStandInPath(string path)
        {
            return paths.Contains(path);
        }

        private static void Save()
        {
            SessionState.SetString(SavedKey, string.Join("\n", paths.ToArray()));
        }

        private static void Update()
        {
            if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling || EditorApplication.isUpdating)
                return;
            if (EditorApplication.timeSinceStartup - lastScan < 10.0)
                return;
            lastScan = EditorApplication.timeSinceStartup;

            if (!TeamSession.IsLinked || !Enabled)
            {
                if (paths.Count > 0 && TeamSession.State == TeamState.Idle)
                    RestoreAll();
                return;
            }

            // Put back any whose real shader has arrived since.
            foreach (var path in paths.ToList())
            {
                string guid = ShaderGuidOf(path);
                if (guid != null && !string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath(guid)))
                    RestoreOne(path);
            }

            // Find pink materials on anything in the open scenes.
            var seen = new HashSet<Material>();
            for (int i = 0; i < EditorSceneManager.sceneCount; i++)
            {
                var scene = EditorSceneManager.GetSceneAt(i);
                if (!scene.isLoaded)
                    continue;
                foreach (var root in scene.GetRootGameObjects())
                    foreach (var renderer in root.GetComponentsInChildren<Renderer>(true))
                        foreach (var material in renderer.sharedMaterials)
                            if (material != null && seen.Add(material))
                                TryStandIn(material);
            }
        }

        private static bool Broken(Material material)
        {
            return material.shader == null || material.shader.name == "Hidden/InternalErrorShader";
        }

        private static void TryStandIn(Material material)
        {
            if (!Broken(material))
                return;
            string path = AssetDatabase.GetAssetPath(material);
            if (string.IsNullOrEmpty(path) || !path.EndsWith(".mat", StringComparison.OrdinalIgnoreCase) || paths.Contains(path))
                return;

            string text;
            try
            {
                text = File.ReadAllText(path);
            }
            catch (Exception)
            {
                return;
            }

            var guid = ShaderGuid.Match(text);
            if (!guid.Success || !string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath(guid.Groups[1].Value)))
                return;

            var shader = Shader.Find("Standard");
            if (shader == null)
                return;

            Texture texture = null;
            var tex = MainTex.Match(text);
            if (tex.Success && tex.Groups[1].Success)
            {
                string texturePath = AssetDatabase.GUIDToAssetPath(tex.Groups[1].Value);
                if (!string.IsNullOrEmpty(texturePath))
                    texture = AssetDatabase.LoadAssetAtPath<Texture>(texturePath);
            }

            var color = Color.white;
            var col = MainColor.Match(text);
            if (col.Success)
            {
                color = new Color(Parse(col.Groups[1].Value), Parse(col.Groups[2].Value), Parse(col.Groups[3].Value), Parse(col.Groups[4].Value));
            }

            var line = ShaderLine.Match(text);
            if (!line.Success)
                return;
            originals[path] = line.Value;
            SaveOriginals();

            paths.Add(path);
            Save();
            material.shader = shader;
            if (texture != null)
                material.mainTexture = texture;
            material.color = color;
            // Nothing for Unity to save: the stand-in lives in memory only.
            EditorUtility.ClearDirty(material);
        }

        private static string OriginalsKey
        {
            get
            {
                using (var md5 = System.Security.Cryptography.MD5.Create())
                    return "WPFMA.Team.StandInOriginals." + BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(Application.dataPath))).Replace("-", string.Empty).Substring(0, 12);
            }
        }

        private static void LoadOriginals()
        {
            foreach (var row in EditorPrefs.GetString(OriginalsKey, string.Empty).Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                int tab = row.IndexOf('\t');
                if (tab > 0)
                    originals[row.Substring(0, tab)] = row.Substring(tab + 1);
            }
        }

        private static void SaveOriginals()
        {
            EditorPrefs.SetString(OriginalsKey, string.Join("\n", originals.Select(p => p.Key + "\t" + p.Value).ToArray()));
        }

        /// <summary>
        /// If a stand-in ever got written into a material file, put the real shader line back. Returns true if the
        /// file was repaired. Called before a material is checked or sent, and on every editor start.
        /// </summary>
        internal static bool RepairIfNeeded(string path)
        {
            string original;
            if (!originals.TryGetValue(path, out original) || !File.Exists(path))
                return false;
            try
            {
                string text = File.ReadAllText(path);
                var line = ShaderLine.Match(text);
                if (!line.Success || line.Value == original)
                    return false;
                File.WriteAllText(path, text.Substring(0, line.Index) + original + text.Substring(line.Index + line.Length));
                Debug.LogWarning("[WPFMA Team] Put the real shader back into " + path + " (a stand-in shader had been saved into it).");
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        internal static void RepairFiles()
        {
            bool any = false;
            foreach (var path in originals.Keys.ToList())
                any |= RepairIfNeeded(path);
            if (any)
                AssetDatabase.Refresh();
        }

        private static float Parse(string value)
        {
            float result;
            return float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result) ? result : 1f;
        }

        private static string ShaderGuidOf(string path)
        {
            try
            {
                var match = ShaderGuid.Match(File.ReadAllText(path));
                return match.Success ? match.Groups[1].Value : null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static void RestoreOne(string path)
        {
            paths.Remove(path);
            Save();
            RepairIfNeeded(path);
            if (File.Exists(path))
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
        }

        internal static void RestoreAll()
        {
            if (paths.Count == 0)
                return;
            foreach (var path in paths.ToList())
                RestoreOne(path);
        }

        /// <summary>The material file was just replaced from the teammate, so it is fresh from disk again.</summary>
        internal static void Forget(string path)
        {
            if (originals.Remove(path))
                SaveOriginals();
            if (paths.Remove(path))
            {
                Save();
                lastScan = -100;
            }
        }
    }

    /// <summary>Stops Unity from ever writing a stand-in material back to disk.</summary>
    internal sealed class TeamStandInSaveGuard : UnityEditor.AssetModificationProcessor
    {
        private static string[] OnWillSaveAssets(string[] paths)
        {
            if (TeamStandIns.Count == 0)
                return paths;
            return paths.Where(p => !TeamStandIns.IsStandInPath(p)).ToArray();
        }
    }
}
#endif
