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

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMASdkDefines
    {
        internal const string AvatarsDefine = "WPFMA_VRC_AVATARS";
        internal const string WorldsDefine = "WPFMA_VRC_WORLDS";

        private static readonly BuildTargetGroup[] Groups =
        {
            BuildTargetGroup.Standalone,
            BuildTargetGroup.Android,
            BuildTargetGroup.iOS
        };

        static WPFMASdkDefines()
        {
            EditorApplication.delayCall += Sync;
        }

        internal static bool AvatarsPresent
        {
            get { return TypeExists("VRC.SDK3.Avatars.Components.VRCAvatarDescriptor"); }
        }

        internal static bool WorldsPresent
        {
            get { return TypeExists("VRC.SDK3.Components.VRCSceneDescriptor"); }
        }

        private static void Sync()
        {
            bool avatars = AvatarsPresent;
            bool worlds = WorldsPresent;

            foreach (var group in Groups)
            {
                NamedBuildTarget target;
                try
                {
                    target = NamedBuildTarget.FromBuildTargetGroup(group);
                }
                catch (Exception)
                {
                    continue;
                }

                string current = PlayerSettings.GetScriptingDefineSymbols(target);
                var defines = new List<string>(current.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));

                bool changed = Apply(defines, AvatarsDefine, avatars) | Apply(defines, WorldsDefine, worlds);
                if (changed)
                    PlayerSettings.SetScriptingDefineSymbols(target, string.Join(";", defines.ToArray()));
            }
        }

        private static bool Apply(List<string> defines, string symbol, bool wanted)
        {
            bool has = defines.Contains(symbol);

            if (wanted && !has)
            {
                defines.Add(symbol);
                return true;
            }

            if (!wanted && has)
            {
                defines.RemoveAll(d => d == symbol);
                return true;
            }

            return false;
        }

        private static bool TypeExists(string name)
        {
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    if (assembly.GetType(name, false) != null)
                        return true;
                }
                catch (Exception)
                {
                }
            }

            return false;
        }
    }
}
#endif
