using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using UdonSharp;
using UnityEngine;
using UnityEngine.TestTools;

// Unity only calls Start on an enabled behaviour, and another behaviour's Start can call into ours
// before our own Start has run. A public method that disables its behaviour at that point means Start
// never runs (the pot and round chip piles stayed empty this way). The other tests call Start by hand,
// so they can't see this.
public class StartOrderTests
{
    private static readonly string[] Assemblies = { "HoldemAssembly", "UdonChipsHat" };

    private static readonly HashSet<string> UnityMessages = new HashSet<string>
    {
        "Awake", "Start", "Update", "LateUpdate", "FixedUpdate", "PostLateUpdate",
        "OnEnable", "OnDisable", "OnDestroy", "OnValidate", "Reset"
    };

    [Test]
    public void NoPublicMethodDisablesItsBehaviourBeforeStart()
    {
        // Unwired behaviours log errors and throw; only the enabled flag matters here.
        LogAssert.ignoreFailingMessages = true;
        var failures = new List<string>();

        foreach (var type in BehavioursWithStart())
        {
            foreach (var method in PublicMethods(type))
            {
                var go = new GameObject(type.Name);
                try
                {
                    var behaviour = (MonoBehaviour)go.AddComponent(type);
                    try { method.Invoke(behaviour, DefaultArguments(method)); }
                    catch (TargetInvocationException) { }
                    if (behaviour != null && !behaviour.enabled) failures.Add(type.Name + "." + method.Name);
                }
                finally
                {
                    if (go != null) Object.DestroyImmediate(go);
                }
            }
        }

        Assert.IsEmpty(failures, "Called before Start, these disable their behaviour, so Unity would never start it:\n  "
            + string.Join("\n  ", failures));
    }

    private static IEnumerable<System.Type> BehavioursWithStart()
    {
        foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
        {
            if (System.Array.IndexOf(Assemblies, assembly.GetName().Name) < 0) continue;
            foreach (var type in assembly.GetTypes())
            {
                if (type.IsAbstract || !typeof(UdonSharpBehaviour).IsAssignableFrom(type)) continue;
                if (type.GetMethod("Start", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                    null, System.Type.EmptyTypes, null) != null) yield return type;
            }
        }
    }

    private static IEnumerable<MethodInfo> PublicMethods(System.Type type)
    {
        foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public))
        {
            if (method.IsSpecialName || method.ContainsGenericParameters) continue;
            if (!typeof(UdonSharpBehaviour).IsAssignableFrom(method.DeclaringType)) continue;
            if (method.DeclaringType == typeof(UdonSharpBehaviour)) continue;
            if (method.GetBaseDefinition().DeclaringType == typeof(UdonSharpBehaviour)) continue;
            if (UnityMessages.Contains(method.Name)) continue;
            yield return method;
        }
    }

    private static object[] DefaultArguments(MethodInfo method)
    {
        var parameters = method.GetParameters();
        var arguments = new object[parameters.Length];
        for (int i = 0; i < parameters.Length; i++)
        {
            var type = parameters[i].ParameterType;
            if (type.IsByRef) type = type.GetElementType();
            arguments[i] = type.IsValueType ? System.Activator.CreateInstance(type) : null;
        }
        return arguments;
    }
}
