// 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 UnityEngine;

#if WPFMA_VRC_AVATARS
using VRC.SDK3.Avatars.Components;
using VRC.SDK3.Dynamics.PhysBone.Components;
#endif

namespace WPFMA
{
    internal static class WPFMAPhysBonePresets
    {
        [Serializable]
        internal sealed class Value
        {
            public string path;
            public string kind;
            public float number;
            public int integer;
            public Vector3 vector;
            public float[] times;
            public float[] values;
            public float[] inTangents;
            public float[] outTangents;
            public float[] inWeights;
            public float[] outWeights;
            public int[] weightedModes;
            public int preWrap;
            public int postWrap;
        }

        [Serializable]
        internal sealed class Preset
        {
            public string name;
            public List<Value> values = new List<Value>();
            [NonSerialized] public bool BuiltIn;
        }

        [Serializable]
        private sealed class PresetFile
        {
            public List<Preset> presets = new List<Preset>();
        }

        internal static readonly string[] Properties =
        {
            "integrationType", "multiChildType", "endpointPosition",
            "pull", "pullCurve", "spring", "springCurve", "stiffness", "stiffnessCurve",
            "gravity", "gravityCurve", "gravityFalloff", "gravityFalloffCurve",
            "immobileType", "immobile", "immobileCurve",
            "allowCollision", "radius", "radiusCurve",
            "limitType", "maxAngleX", "maxAngleXCurve", "maxAngleZ", "maxAngleZCurve",
            "limitRotation", "limitRotationXCurve", "limitRotationYCurve", "limitRotationZCurve",
            "allowGrabbing", "allowPosing", "grabMovement", "snapToHand",
            "maxStretch", "maxStretchCurve", "maxSquish", "maxSquishCurve", "stretchMotion", "stretchMotionCurve",
            "isAnimated", "resetWhenDisabled"
        };

        private static List<Preset> userPresets;

        internal static string StorePath
        {
            get
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "WPFMA-SDK", "physbone-presets.json");
            }
        }

        internal static List<Preset> All()
        {
            return BuiltIns().Concat(User()).ToList();
        }

        internal static List<Preset> User()
        {
            if (userPresets != null)
                return userPresets;

            userPresets = new List<Preset>();
            try
            {
                if (File.Exists(StorePath))
                {
                    var file = JsonUtility.FromJson<PresetFile>(File.ReadAllText(StorePath));
                    if (file != null && file.presets != null)
                        userPresets = file.presets.Where(p => p != null && !string.IsNullOrEmpty(p.name)).ToList();
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not read the PhysBone presets file: " + e.Message);
            }

            return userPresets;
        }

        internal static void SaveUser(Preset preset)
        {
            var list = User();
            list.RemoveAll(p => string.Equals(p.name, preset.name, StringComparison.OrdinalIgnoreCase));
            list.Add(preset);
            list.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase));
            Write(list);
        }

        internal static void DeleteUser(string name)
        {
            var list = User();
            list.RemoveAll(p => string.Equals(p.name, name, StringComparison.OrdinalIgnoreCase));
            Write(list);
        }

        internal static bool IsBuiltInName(string name)
        {
            return BuiltIns().Any(p => string.Equals(p.name, name, StringComparison.OrdinalIgnoreCase));
        }

        private static void Write(List<Preset> list)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(StorePath));
            File.WriteAllText(StorePath, JsonUtility.ToJson(new PresetFile { presets = list }, true));
        }

        internal static Preset Capture(UnityEngine.Object physBone, string name)
        {
            var preset = new Preset { name = name };
            var serialized = new SerializedObject(physBone);

            foreach (var path in Properties)
            {
                var property = serialized.FindProperty(path);
                if (property == null)
                    continue;

                var value = new Value { path = path };
                switch (property.propertyType)
                {
                    case SerializedPropertyType.Float:
                        value.kind = "float";
                        value.number = property.floatValue;
                        break;
                    case SerializedPropertyType.Integer:
                    case SerializedPropertyType.Enum:
                        value.kind = "int";
                        value.integer = property.intValue;
                        break;
                    case SerializedPropertyType.Boolean:
                        value.kind = "bool";
                        value.integer = property.boolValue ? 1 : 0;
                        break;
                    case SerializedPropertyType.Vector3:
                        value.kind = "vector";
                        value.vector = property.vector3Value;
                        break;
                    case SerializedPropertyType.AnimationCurve:
                        value.kind = "curve";
                        StoreCurve(value, property.animationCurveValue);
                        break;
                    default:
                        continue;
                }

                preset.values.Add(value);
            }

            return preset;
        }

        internal static void Apply(Preset preset, UnityEngine.Object physBone)
        {
            var serialized = new SerializedObject(physBone);

            foreach (var value in preset.values)
            {
                var property = serialized.FindProperty(value.path);
                if (property == null)
                    continue;

                switch (value.kind)
                {
                    case "float":
                        if (property.propertyType == SerializedPropertyType.Float)
                            property.floatValue = value.number;
                        break;
                    case "int":
                        if (property.propertyType == SerializedPropertyType.Integer ||
                            property.propertyType == SerializedPropertyType.Enum)
                            property.intValue = value.integer;
                        break;
                    case "bool":
                        if (property.propertyType == SerializedPropertyType.Boolean)
                            property.boolValue = value.integer != 0;
                        break;
                    case "vector":
                        if (property.propertyType == SerializedPropertyType.Vector3)
                            property.vector3Value = value.vector;
                        break;
                    case "curve":
                        if (property.propertyType == SerializedPropertyType.AnimationCurve)
                            property.animationCurveValue = LoadCurve(value);
                        break;
                }
            }

            serialized.ApplyModifiedProperties();
        }

        private static void StoreCurve(Value value, AnimationCurve curve)
        {
            var keys = curve != null ? curve.keys : new Keyframe[0];
            value.times = keys.Select(k => k.time).ToArray();
            value.values = keys.Select(k => k.value).ToArray();
            value.inTangents = keys.Select(k => k.inTangent).ToArray();
            value.outTangents = keys.Select(k => k.outTangent).ToArray();
            value.inWeights = keys.Select(k => k.inWeight).ToArray();
            value.outWeights = keys.Select(k => k.outWeight).ToArray();
            value.weightedModes = keys.Select(k => (int)k.weightedMode).ToArray();
            value.preWrap = curve != null ? (int)curve.preWrapMode : 0;
            value.postWrap = curve != null ? (int)curve.postWrapMode : 0;
        }

        private static AnimationCurve LoadCurve(Value value)
        {
            int count = value.times != null ? value.times.Length : 0;
            var keys = new Keyframe[count];
            for (int i = 0; i < count; i++)
            {
                keys[i] = new Keyframe(value.times[i], value.values[i], value.inTangents[i], value.outTangents[i],
                    value.inWeights[i], value.outWeights[i])
                {
                    weightedMode = (WeightedMode)value.weightedModes[i]
                };
            }

            return new AnimationCurve(keys)
            {
                preWrapMode = (WrapMode)value.preWrap,
                postWrapMode = (WrapMode)value.postWrap
            };
        }

        private static List<Preset> builtIns;

        private static List<Preset> BuiltIns()
        {
            if (builtIns != null)
                return builtIns;

            builtIns = new List<Preset>
            {
                Make("Hair", 0.2f, 0.2f, 0.2f, 0.1f, 0.6f, 0.3f, 0.02f, 45f, true),
                Make("Long hair", 0.15f, 0.3f, 0.1f, 0.2f, 0.5f, 0.2f, 0.02f, 60f, true),
                Make("Tail", 0.2f, 0.4f, 0.2f, 0.1f, 0.8f, 0.1f, 0.04f, 80f, true),
                Make("Skirt", 0.3f, 0.1f, 0.3f, 0.3f, 0.5f, 0.5f, 0.03f, 45f, false),
                Make("Ears", 0.4f, 0.2f, 0.5f, 0f, 0f, 0.4f, 0.02f, 30f, true),
                Make("Stiff accessory", 0.6f, 0.1f, 0.7f, 0f, 0f, 0.6f, 0.02f, 20f, true)
            };

            return builtIns;
        }

        private static Preset Make(string name, float pull, float momentum, float stiffness, float gravity,
            float falloff, float immobile, float radius, float angle, bool grabbable)
        {
            var preset = new Preset { name = name, BuiltIn = true };
            preset.values.Add(new Value { path = "integrationType", kind = "int", integer = 0 });
            preset.values.Add(new Value { path = "pull", kind = "float", number = pull });
            preset.values.Add(new Value { path = "spring", kind = "float", number = momentum });
            preset.values.Add(new Value { path = "stiffness", kind = "float", number = stiffness });
            preset.values.Add(new Value { path = "gravity", kind = "float", number = gravity });
            preset.values.Add(new Value { path = "gravityFalloff", kind = "float", number = falloff });
            preset.values.Add(new Value { path = "immobileType", kind = "int", integer = 0 });
            preset.values.Add(new Value { path = "immobile", kind = "float", number = immobile });
            preset.values.Add(new Value { path = "radius", kind = "float", number = radius });
            preset.values.Add(new Value { path = "allowCollision", kind = "int", integer = 1 });
            preset.values.Add(new Value { path = "limitType", kind = "int", integer = 1 });
            preset.values.Add(new Value { path = "maxAngleX", kind = "float", number = angle });
            preset.values.Add(new Value { path = "allowGrabbing", kind = "int", integer = grabbable ? 1 : 0 });
            preset.values.Add(new Value { path = "allowPosing", kind = "int", integer = grabbable ? 1 : 0 });
            return preset;
        }
    }

    internal static class WPFMAPhysBoneSection
    {
        private const string PrefKey = "WPFMA.Tools.PhysBonesExpanded";

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;

            WPFMAToolSection.Draw(sectionStyle, "PhysBones", Detail(), PrefKey, Body);
        }

#if !WPFMA_VRC_AVATARS
        private static string Detail()
        {
            return "needs the avatar SDK";
        }

        private static void Body()
        {
            EditorGUILayout.HelpBox("This needs the VRChat avatar SDK, which is not in this project yet.", MessageType.Info);
        }
#else
        private static int presetIndex;
        private static string search = string.Empty;
        private static string newPresetName = string.Empty;
        private static bool updateExisting { get { return WPFMAToolDefaults.PhysBonesUpdateExisting; } set { WPFMAToolDefaults.PhysBonesUpdateExisting = value; } }
        private static string status;
        private static bool statusIsError;

        private static string Detail()
        {
            var bones = Selected();
            return bones.Count == 0 ? "nothing selected" : bones.Count + (bones.Count == 1 ? " bone selected" : " bones selected");
        }

        private static List<Transform> Selected()
        {
            return Selection.transforms
                .Where(t => t != null && !EditorUtility.IsPersistent(t) && t.GetComponentInParent<VRCAvatarDescriptor>() != null)
                .ToList();
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("PhysBones in one click, with presets.", "Adds PhysBones to hair, tails, skirts and the like with one click. Save any PhysBone you like as " + "your own preset - presets are kept on this PC and show up in every project."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            DrawFinder();
            EditorGUILayout.Space(6f);
            DrawApply();
            EditorGUILayout.Space(6f);
            DrawSave();

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

        private static void DrawFinder()
        {
            EditorGUILayout.LabelField("1. Pick the bones", EditorStyles.boldLabel);

            var active = Selection.activeGameObject;
            var avatar = active != null && !EditorUtility.IsPersistent(active) ? active.GetComponentInParent<VRCAvatarDescriptor>() : null;

            using (new EditorGUILayout.HorizontalScope())
            {
                search = EditorGUILayout.TextField("Find bones named", search);
                using (new EditorGUI.DisabledScope(avatar == null || string.IsNullOrWhiteSpace(search)))
                {
                    if (GUILayout.Button("Select", GUILayout.Width(60f)))
                        SelectChains(avatar, search.Trim());
                }
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(EditorGUIUtility.labelWidth);
                foreach (var word in new[] { "hair", "tail", "skirt", "ear" })
                {
                    using (new EditorGUI.DisabledScope(avatar == null))
                    {
                        if (GUILayout.Button(word, EditorStyles.miniButton))
                        {
                            search = word;
                            SelectChains(avatar, word);
                        }
                    }
                }
            }

            EditorGUILayout.LabelField(
                avatar == null
                    ? new GUIContent("Select the avatar or the bones.", "Select the avatar or any bone in it first. Or just select the bones yourself in the Hierarchy.")
                    : new GUIContent("Picks each chain's first bone.", "Picks the first bone of each matching chain. Or select bones yourself in the Hierarchy."),
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
        }

        private static void DrawApply()
        {
            EditorGUILayout.LabelField("2. Pick a preset and add", EditorStyles.boldLabel);

            var presets = WPFMAPhysBonePresets.All();
            presetIndex = Mathf.Clamp(presetIndex, 0, presets.Count - 1);

            var labels = presets.Select(p => p.BuiltIn ? p.name : p.name + "  (mine)").ToArray();
            using (new EditorGUILayout.HorizontalScope())
            {
                presetIndex = EditorGUILayout.Popup("Preset", presetIndex, labels);

                var chosen = presets[presetIndex];
                using (new EditorGUI.DisabledScope(chosen.BuiltIn))
                {
                    if (GUILayout.Button("Delete", GUILayout.Width(60f)))
                    {
                        string name = chosen.name;
                        EditorApplication.delayCall += () =>
                        {
                            if (!EditorUtility.DisplayDialog("Delete preset", "Delete your preset '" + name + "'?", "Delete", "Cancel"))
                                return;

                            WPFMAPhysBonePresets.DeleteUser(name);
                            presetIndex = 0;
                            status = "Deleted '" + name + "'.";
                            statusIsError = false;
                        };
                    }
                }
            }

            var bones = Selected();
            int existing = bones.Count(b => b.GetComponent<VRCPhysBone>() != null);

            updateExisting = EditorGUILayout.ToggleLeft(
                "Also apply it to PhysBones already on the selected bones" + (existing > 0 ? "  (" + existing + ")" : string.Empty),
                updateExisting);

            using (new EditorGUI.DisabledScope(bones.Count == 0))
            {
                string label = bones.Count == 0
                    ? "Select bones first"
                    : "Add to " + bones.Count + (bones.Count == 1 ? " bone" : " bones");

                if (GUILayout.Button(label, GUILayout.Height(26f)))
                {
                    var preset = presets[presetIndex];
                    var targets = bones.ToList();
                    bool update = updateExisting;
                    EditorApplication.delayCall += () => WPFMAChangeLog.Run("PhysBones", "Add '" + preset.name + "' to " + targets.Count + " bone(s)",
                        null, true, () => { AddTo(targets, preset, update); return status; });
                }
            }
        }

        private static void DrawSave()
        {
            EditorGUILayout.LabelField("Save a PhysBone as a preset", EditorStyles.boldLabel);

            var source = Selection.activeGameObject != null ? Selection.activeGameObject.GetComponent<VRCPhysBone>() : null;

            using (new EditorGUILayout.HorizontalScope())
            {
                newPresetName = EditorGUILayout.TextField("Name", newPresetName);
                using (new EditorGUI.DisabledScope(source == null || string.IsNullOrWhiteSpace(newPresetName)))
                {
                    if (GUILayout.Button("Save", GUILayout.Width(60f)))
                    {
                        string name = newPresetName.Trim();
                        if (WPFMAPhysBonePresets.IsBuiltInName(name))
                            name += " (mine)";

                        WPFMAPhysBonePresets.SaveUser(WPFMAPhysBonePresets.Capture(source, name));
                        status = "Saved '" + name + "'. It is in the preset list in every project on this PC.";
                        statusIsError = false;
                        newPresetName = string.Empty;
                        presetIndex = WPFMAPhysBonePresets.All().FindIndex(p => p.name == name);
                    }
                }
            }

            EditorGUILayout.LabelField(
                source == null
                    ? new GUIContent("Select a bone with a PhysBone to save it.", "Select a bone that has a PhysBone you like, then name it and save.")
                    : new GUIContent("Saves '" + source.name + "'.", "Saves the settings of the PhysBone on '" + source.name + "'. Same name replaces your old one."),
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (GUILayout.Button("Show presets file", EditorStyles.miniButton, GUILayout.Width(130f)))
            {
                string path = WPFMAPhysBonePresets.StorePath;
                EditorUtility.RevealInFinder(File.Exists(path) ? path : Path.GetDirectoryName(path));
            }
        }

        private static void AddTo(List<Transform> bones, WPFMAPhysBonePresets.Preset preset, bool update)
        {
            Undo.SetCurrentGroupName("Add PhysBones");
            int group = Undo.GetCurrentGroup();
            int added = 0, updated = 0;

            foreach (var bone in bones)
            {
                if (bone == null)
                    continue;

                var physBone = bone.GetComponent<VRCPhysBone>();
                if (physBone == null)
                {
                    physBone = Undo.AddComponent<VRCPhysBone>(bone.gameObject);
                    added++;
                }
                else if (update)
                {
                    updated++;
                }
                else
                {
                    continue;
                }

                WPFMAPhysBonePresets.Apply(preset, physBone);
            }

            Undo.CollapseUndoOperations(group);

            status = "'" + preset.name + "': added " + added + (updated > 0 ? ", updated " + updated : string.Empty) + ".";
            statusIsError = added + updated == 0;
        }

        private static bool NameMatches(string name, string word)
        {
            return System.Text.RegularExpressions.Regex.Split(name.ToLowerInvariant(), "[^a-z]+")
                .Any(token => token.StartsWith(word, StringComparison.Ordinal));
        }

        private static void SelectChains(VRCAvatarDescriptor avatar, string word)
        {
            if (avatar == null)
                return;

            string lower = word.ToLowerInvariant();
            var roots = avatar.GetComponentsInChildren<Transform>(true)
                .Where(t => t != avatar.transform && NameMatches(t.name, lower))
                .Where(t => t.parent == null || !NameMatches(t.parent.name, lower))
                .Where(t => t.GetComponent<Renderer>() == null && t.childCount > 0)
                .Select(t => (UnityEngine.Object)t.gameObject)
                .ToArray();

            if (roots.Length == 0)
            {
                status = "No bones with '" + word + "' in their name.";
                statusIsError = true;
                return;
            }

            Selection.objects = roots;
            status = "Selected " + roots.Length + " '" + word + "' " + (roots.Length == 1 ? "chain." : "chains.");
            statusIsError = false;
        }
#endif
    }
}
#endif
