using NUnit.Framework;
using UnityEditor;
using UnityEngine;

// All four rank indices of a dealt hand (top-left and bottom-right of both hole cards) must be readable, with the
// winner / hand highlight rings lit, in every pose the hand can settle into: the saved prefab, the end of Deal.anim
// and HandIdle.anim. The geometry comes from CardNumberVisibility (alpha-mask based, see CardSilhouette).
//
// The saved prefab pose, the animation end poses and the highlight objects must also agree with each other, so a
// later edit to one of them cannot silently reintroduce an overlap in another.
public class HandCardNumberVisibilityTests
{
    private static string HandPath => CardRigRecenter.HandPrefabPath;
    private const string DealPath = "Assets/VrchatHoldem/Animations/Deal.anim";
    private const string IdlePath = "Assets/VrchatHoldem/Animations/HandIdle.anim";

    // The index box is the full printed rank plus suit pip, so it is a little larger than the ink. At the chosen
    // 30 mm spacing the winner ring comes within 0.9 mm of the box (checked by eye on renders of the 10), so up to
    // 1 mm of overlap with the box is accepted; anything more means a number is actually being covered.
    private const float Margin = -0.001f;
    private const float PoseTolerance = 1e-5f;

    private static void WithHand(System.Action<GameObject> body)
    {
        GameObject root = PrefabUtility.LoadPrefabContents(HandPath);
        try { body(root); }
        finally { PrefabUtility.UnloadPrefabContents(root); }
    }

    private static AnimationClip Clip(string path)
    {
        var clip = AssetDatabase.LoadAssetAtPath<AnimationClip>(path);
        Assert.IsNotNull(clip, path + " missing");
        return clip;
    }

    private static void AssertAllVisible(CardNumberVisibility.Rig rig, CardNumberVisibility.Pose card0,
        CardNumberVisibility.Pose card1, string what)
    {
        foreach (bool winner in new[] { false, true })
        foreach (bool hand in new[] { false, true })
        {
            CardNumberVisibility.Report report = CardNumberVisibility.Evaluate(rig, card0, card1, winner, hand, Margin);
            Assert.IsTrue(report.AllVisible,
                what + " (winner ring " + (winner ? "on" : "off") + ", hand ring " + (hand ? "on" : "off") + "): " +
                string.Join("; ", report.hidden));
        }
    }

    private static void ClipEndPoses(AnimationClip clip, out CardNumberVisibility.Pose card0, out CardNumberVisibility.Pose card1)
    {
        Assert.IsTrue(CardNumberVisibility.TryReadClipPose(clip, 0, clip.length, out card0), clip.name + " has no Card0 pose curves");
        Assert.IsTrue(CardNumberVisibility.TryReadClipPose(clip, 1, clip.length, out card1), clip.name + " has no Card1 pose curves");
    }

    private static void AssertPoseEqual(CardNumberVisibility.Pose expected, CardNumberVisibility.Pose actual, string what)
    {
        Assert.AreEqual(expected.position.x, actual.position.x, PoseTolerance, what + " x");
        Assert.AreEqual(expected.position.y, actual.position.y, PoseTolerance, what + " y");
        Assert.AreEqual(expected.position.z, actual.position.z, PoseTolerance, what + " z");
        Assert.AreEqual(0f, Mathf.DeltaAngle(expected.yaw, actual.yaw), 1e-3f, what + " yaw");
    }

    // ---- every pose the hand settles into ----

    [Test]
    public void SavedPrefab_AllFourNumbersVisible()
    {
        WithHand(root => AssertAllVisible(CardNumberVisibility.Build(root),
            CardNumberVisibility.ReadPose(root, 0), CardNumberVisibility.ReadPose(root, 1), "Hand.prefab"));
    }

    [Test]
    public void DealEnd_AllFourNumbersVisible()
    {
        CardNumberVisibility.Pose card0, card1;
        ClipEndPoses(Clip(DealPath), out card0, out card1);
        WithHand(root => AssertAllVisible(CardNumberVisibility.Build(root), card0, card1, "Deal.anim end"));
    }

    [Test]
    public void HandIdle_AllFourNumbersVisible()
    {
        CardNumberVisibility.Pose card0, card1;
        ClipEndPoses(Clip(IdlePath), out card0, out card1);
        WithHand(root => AssertAllVisible(CardNumberVisibility.Build(root), card0, card1, "HandIdle.anim"));
    }

    // ---- everything agrees on where the cards are ----

    [Test]
    public void Animations_EndOnThePrefabPose([Values(DealPath, IdlePath)] string clipPath, [Values(0, 1)] int cardIndex)
    {
        CardNumberVisibility.Pose card0, card1;
        ClipEndPoses(Clip(clipPath), out card0, out card1);
        WithHand(root => AssertPoseEqual(CardNumberVisibility.ReadPose(root, cardIndex), cardIndex == 0 ? card0 : card1,
            clipPath + " Card" + cardIndex));
    }

    [Test]
    public void Highlights_SitOnTheirCardsPose([Values("Highlight", "HighlightHand")] string set, [Values(0, 1)] int cardIndex)
    {
        WithHand(root =>
        {
            CardNumberVisibility.Pose card = CardNumberVisibility.ReadPose(root, cardIndex);
            Transform t = root.transform.Find(set + "/HighlightCard" + cardIndex);
            Assert.IsNotNull(t, set + "/HighlightCard" + cardIndex + " missing");
            Assert.AreEqual(card.position.x, t.localPosition.x, PoseTolerance, set + " x");
            Assert.AreEqual(card.position.y, t.localPosition.y, PoseTolerance, set + " y");
            Assert.AreEqual(card.position.z, t.localPosition.z, PoseTolerance, set + " z");
            Assert.AreEqual(0f, Mathf.DeltaAngle(card.yaw, t.localEulerAngles.y), 1e-3f, set + " yaw");
        });
    }

    // ---- the harness itself must be able to fail ----

    [Test]
    public void Harness_FlagsTheOldOverlappingLayout()
    {
        // cards 26 mm either side of center overlap far enough for the upper card to sit on the lower card's
        // top-left index
        var card0 = new CardNumberVisibility.Pose { position = new Vector3(-0.03f, 0.001f, -0.026f), yaw = -5f };
        var card1 = new CardNumberVisibility.Pose { position = new Vector3(-0.03f, 0f, 0.026f), yaw = 5f };
        WithHand(root =>
        {
            CardNumberVisibility.Report report = CardNumberVisibility.Evaluate(CardNumberVisibility.Build(root), card0, card1, true, true, Margin);
            Assert.IsFalse(report.AllVisible, "the harness should see the top-left index of Card1 under Card0 / its ring");
        });
    }

    [Test]
    public void Harness_FlagsADealEndWhereTheLowerCardHidesTheOther()
    {
        // Deal.anim used to end with Card1 above Card0 (y 0 vs -0.001) and the cards 25 mm from center
        var card0 = new CardNumberVisibility.Pose { position = new Vector3(-0.03f, -0.001f, -0.025f), yaw = -5f };
        var card1 = new CardNumberVisibility.Pose { position = new Vector3(-0.03f, 0f, 0.025f), yaw = 5f };
        WithHand(root =>
        {
            CardNumberVisibility.Report report = CardNumberVisibility.Evaluate(CardNumberVisibility.Build(root), card0, card1, false, false, Margin);
            Assert.IsFalse(report.AllVisible, "the harness should see Card0's bottom-right index under Card1");
        });
    }
}
