using UnityEditor;
using UnityEngine;

namespace PleasureArcade.ThiccWater
{
    public class AnimationClipEditor
    {
        private const float phi = 0.618034f;
        
        public static void RegroupAnimation(string oldPath, string newPath, string emitter, string group, int count)
        {
            AssetDatabase.CopyAsset(oldPath, newPath);
            var anim = AssetDatabase.LoadAssetAtPath<AnimationClip>(newPath);

            var bindings = AnimationUtility.GetCurveBindings(anim);
            foreach (var binding in bindings)
            {
                // For emitter bindings, create copies of the curve for each emitter, then remove original
                if (!binding.path.Contains("/" + emitter + "/")) continue;

                var curve = AnimationUtility.GetEditorCurve(anim, binding);
                var keyframes = curve.keys; 
                    
                for (var i = 0; i < count; i++)
                {
                    // Special case: ScreenShader & ClearBuffer are removed for all but parent 0
                    if (i > 0 && (binding.path.EndsWith("ScreenShader") || binding.path.EndsWith("ClearBuffer")))
                    {
                        continue;
                    }
                    
                    var newBinding = new EditorCurveBinding()
                    {
                        path = binding.path.Replace("ThiccWater/" + emitter, "ThiccWater/" + group + "/Parent" + i + "/" + emitter + i),
                        propertyName = binding.propertyName,
                        type = binding.type
                    };
                    
                    // Special case for Drip: Offset each parented emitter by (phi * i) % 1
                    if ((emitter == "Drip" || emitter == "WhiteDrip") && binding.propertyName == "material._FakeTime")
                    {
                        var adjustedKeys = (Keyframe[])keyframes.Clone();
                        for (var j = 0; j < curve.keys.Length; j++)
                        {
                            adjustedKeys[j].value += (phi * i) % 1.0f;
                        }

                        curve.keys = adjustedKeys;
                    }

                    AnimationUtility.SetEditorCurve(anim, newBinding, curve);
                }
                
                AnimationUtility.SetEditorCurve(anim, binding, null);
            }

            AssetDatabase.SaveAssets();
        }
    }
}