// 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.IO;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    internal static class WPFMAAvatarFolders
    {
        internal static GameObject AvatarRoot(GameObject selected)
        {
            if (selected == null || EditorUtility.IsPersistent(selected))
                return null;

            Transform best = null;
            for (var current = selected.transform; current != null; current = current.parent)
            {
                foreach (var component in current.GetComponents<Component>())
                {
                    if (component != null && component.GetType().Name == "VRCAvatarDescriptor")
                        return current.gameObject;
                }

                if (current.GetComponent<Animator>() != null)
                    best = current;
            }

            return best != null ? best.gameObject : null;
        }

        internal static string For(GameObject root)
        {
            string name = WPFMAPaths.SafeFileName(root != null ? root.name : "Avatar");

            var source = root != null ? PrefabUtility.GetCorrespondingObjectFromOriginalSource(root) : null;
            string path = source != null ? AssetDatabase.GetAssetPath(source) : null;
            if (!string.IsNullOrEmpty(path) && path.StartsWith("Assets/") && !path.StartsWith("Assets/WPFMA-SDK/"))
                return Path.GetDirectoryName(path).Replace('\\', '/') + "/" + name + " VRC";

            return "Assets/Avatars/" + name;
        }

        internal static void Ensure(string folder)
        {
            if (AssetDatabase.IsValidFolder(folder))
                return;

            string parent = Path.GetDirectoryName(folder).Replace('\\', '/');
            if (!AssetDatabase.IsValidFolder(parent))
                Ensure(parent);

            AssetDatabase.CreateFolder(parent, Path.GetFileName(folder));
        }
    }
}
#endif
