using System.Reflection;
using NUnit.Framework;
using UnityEngine;

public class GrabbablePileTests
{
    private GameObject root;
    private GrabbablePile grabbable;

    [SetUp]
    public void SetUp()
    {
        root = new GameObject("GrabbablePileTest");
        grabbable = root.AddComponent<GrabbablePile>();
    }

    [TearDown]
    public void TearDown()
    {
        Object.DestroyImmediate(root);
    }

    [Test]
    public void CallController_HasNoDenominationSourceResponsibilities()
    {
        BindingFlags fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
        Assert.IsNull(typeof(GrabbablePile).GetField("sourcePile", fields));
        Assert.IsNull(typeof(GrabbablePile).GetField("denominationZones", fields));
        Assert.IsNull(typeof(GrabbablePile).GetField("denominationColliders", fields));
        MethodInfo inputUse = typeof(GrabbablePile).GetMethod("InputUse", fields);
        Assert.AreNotEqual(typeof(GrabbablePile), inputUse.DeclaringType);
    }

    [Test]
    public void PhysicalAvailability_ControlsOnlyTheCallCollider()
    {
        BoxCollider callCollider = root.AddComponent<BoxCollider>();
        grabbable.ownCollider = callCollider;

        grabbable.SetPhysicalBettingEnabled(true);
        grabbable.SetPhysicalGrabbable(true);
        Assert.IsTrue(callCollider.enabled);
        Assert.IsTrue(grabbable.DisableInteractive,
            "Physical calls must use pickup/drop rather than Udon Interact");

        grabbable.SetPhysicalGrabbable(false);
        Assert.IsFalse(callCollider.enabled);
    }

    [Test]
    public void StaleReturnCallback_DoesNotCancelNewerPickup()
    {
        VrcRuntimeFake.SetPrivate(grabbable, "trackingCollision", true);
        VrcRuntimeFake.SetPrivate(grabbable, "pendingReturnToken", 2);
        VrcRuntimeFake.SetPrivate(grabbable, "dropToken", 3);

        grabbable._MoveBackToInitialPosition();

        Assert.IsTrue((bool)VrcRuntimeFake.GetPrivate(grabbable, "trackingCollision"));
    }

    [Test]
    public void DisablingPhysicalMode_RestoresLegacyCallCollider()
    {
        BoxCollider callCollider = root.AddComponent<BoxCollider>();
        grabbable.ownCollider = callCollider;

        grabbable.SetPhysicalBettingEnabled(true);
        grabbable.SetPhysicalGrabbable(false);
        grabbable.SetPhysicalBettingEnabled(false);

        Assert.IsTrue(callCollider.enabled);
    }
}
