using NUnit.Framework;
using UnityEditor;
using UnityEngine;

// The highlight meshes exist in the prefabs; these pin how they are wired.
//
//  - Every PlayingCard points at its own HighlightCard child, so PlayingCard.SetHighlighted drives it.
//  - Hand highlight meshes are skinned onto the SAME bones as the card they belong to, so
//    GrabbableHand's peek-fold bending (which moves those bones) bends the highlight with the card.
public class HandHighlightPrefabTests
{
    private static string HandPath => HoldemPaths.Asset("DevPrefabs/Hand.prefab");
    private static string CenterPath => HoldemPaths.Asset("DevPrefabs/CardsCenter.prefab");
    private static string UiPath => HoldemPaths.Asset("DevPrefabs/CardsMesh.prefab");

    private static readonly string[] BoardCardNames = { "Flop1", "Flop2", "Flop3", "Turn", "River" };

    private static Transform Find(GameObject root, string path)
    {
        var t = root.transform.Find(path);
        Assert.IsNotNull(t, path + " missing in " + root.name);
        return t;
    }

    private static void WithPrefab(string path, System.Action<GameObject> body)
    {
        GameObject root = PrefabUtility.LoadPrefabContents(path);
        try { body(root); }
        finally { PrefabUtility.UnloadPrefabContents(root); }
    }

    // ---- wiring ----

    [Test]
    public void Hand_HoleCardsPointAtTheirOwnHighlightCards()
    {
        WithPrefab(HandPath, root =>
        {
            var hand = root.GetComponent<GrabbableHand>();
            Assert.IsNotNull(hand);
            Assert.AreEqual(Find(root, "Card0").GetComponent<PlayingCard>(), hand.hole0);
            Assert.AreEqual(Find(root, "Card1").GetComponent<PlayingCard>(), hand.hole1);

            Assert.AreSame(Find(root, "HighlightHand/HighlightCard0").gameObject, hand.hole0.highlight);
            Assert.AreSame(Find(root, "HighlightHand/HighlightCard1").gameObject, hand.hole1.highlight);
        });
    }

    [Test]
    public void Hand_WinnerGlowIsStillThere()
    {
        // regression: the older whole-hand winner highlight is unrelated to this feature
        WithPrefab(HandPath, root =>
        {
            Find(root, "Highlight/HighlightCard0");
            Find(root, "Highlight/HighlightCard1");
        });
    }

    [Test]
    public void CardsCenter_EveryBoardCardPointsAtItsOwnHighlight()
    {
        WithPrefab(CenterPath, root =>
        {
            foreach (var name in BoardCardNames)
            {
                var card = Find(root, name).GetComponent<PlayingCard>();
                Assert.IsNotNull(card, name);
                Assert.AreSame(Find(root, name + "/HighlightCard").gameObject, card.highlight, name);
            }
        });
    }

    [Test]
    public void CardsMesh_EveryBoardCardPointsAtItsOwnHighlight()
    {
        WithPrefab(UiPath, root =>
        {
            foreach (var name in new[] { "Flop1", "Flop2", "Flop3", "Turn", "River" })
            {
                var card = Find(root, name).GetComponent<PlayingCard>();
                Assert.IsNotNull(card, name);
                Assert.AreSame(Find(root, name + "/HighlightCard").gameObject, card.highlight, name);
            }
        });
    }

    [Test]
    public void CardsCenter_ControllerStillReferencesTheSameCards()
    {
        // regression: highlight wiring must not disturb the flip controller's card slots
        WithPrefab(CenterPath, root =>
        {
            var ctl = root.GetComponent<TableCardFlipController>();
            Assert.AreEqual(Find(root, "Flop1").GetComponent<PlayingCard>(), ctl.flopCard0);
            Assert.AreEqual(Find(root, "Flop2").GetComponent<PlayingCard>(), ctl.flopCard1);
            Assert.AreEqual(Find(root, "Flop3").GetComponent<PlayingCard>(), ctl.flopCard2);
            Assert.AreEqual(Find(root, "Turn").GetComponent<PlayingCard>(), ctl.turnCard);
            Assert.AreEqual(Find(root, "River").GetComponent<PlayingCard>(), ctl.riverCard);
        });
    }

    [Test]
    public void CardsMesh_ControllerStillReferencesTheSameCards()
    {
        WithPrefab(UiPath, root =>
        {
            var ctl = root.GetComponent<CardFlipController>();
            Assert.AreEqual(Find(root, "Flop1").GetComponent<PlayingCard>(), ctl.flopCard0);
            Assert.AreEqual(Find(root, "Flop2").GetComponent<PlayingCard>(), ctl.flopCard1);
            Assert.AreEqual(Find(root, "Flop3").GetComponent<PlayingCard>(), ctl.flopCard2);
            Assert.AreEqual(Find(root, "Turn").GetComponent<PlayingCard>(), ctl.turnCard);
            Assert.AreEqual(Find(root, "River").GetComponent<PlayingCard>(), ctl.riverCard);
        });
    }

    // ---- bending (option A: skinned onto the card's own bones) ----

    private static void AssertSkinnedLikeTheCard(GameObject root, string card, string highlight, string face)
    {
        var source = Find(root, card + "/" + face).GetComponent<SkinnedMeshRenderer>();
        var glow = Find(root, highlight + "/" + face).GetComponent<SkinnedMeshRenderer>();
        string label = highlight + "/" + face;

        Assert.IsNotNull(source, card + "/" + face + " is expected to be skinned");
        Assert.IsNotNull(glow, label + " must be a SkinnedMeshRenderer or it cannot bend");
        Assert.IsNull(Find(root, highlight + "/" + face).GetComponent<MeshRenderer>(), label + " still has a static MeshRenderer");

        Assert.IsNotNull(glow.sharedMesh, label + " mesh");
        Assert.AreEqual(source.sharedMesh.vertexCount, glow.sharedMesh.vertexCount, label + " must match the card's vertices");
        Assert.AreEqual(source.sharedMesh.boneWeights.Length, glow.sharedMesh.boneWeights.Length, label + " needs the same skin weights");
        Assert.Greater(glow.sharedMesh.boneWeights.Length, 0, label + " has no skin weights");

        Assert.AreEqual(source.bones.Length, glow.bones.Length, label + " bone count");
        for (int i = 0; i < source.bones.Length; i++)
            Assert.AreSame(source.bones[i], glow.bones[i], label + " bone " + i + " must be the card's own bone");
        Assert.AreSame(source.rootBone, glow.rootBone, label + " root bone");
    }

    [Test]
    public void Hand_HighlightCard0BendsWithCard0()
    {
        WithPrefab(HandPath, root =>
        {
            AssertSkinnedLikeTheCard(root, "Card0", "HighlightHand/HighlightCard0", "Back");
            AssertSkinnedLikeTheCard(root, "Card0", "HighlightHand/HighlightCard0", "FrontBlank");
        });
    }

    [Test]
    public void Hand_HighlightCard1BendsWithCard1()
    {
        WithPrefab(HandPath, root =>
        {
            AssertSkinnedLikeTheCard(root, "Card1", "HighlightHand/HighlightCard1", "Back");
            AssertSkinnedLikeTheCard(root, "Card1", "HighlightHand/HighlightCard1", "FrontBlank");
        });
    }

    [Test]
    public void Hand_WinnerGlowBendsWithItsCards()
    {
        WithPrefab(HandPath, root =>
        {
            foreach (var face in new[] { "Back", "FrontBlank" })
            {
                AssertSkinnedLikeTheCard(root, "Card0", "Highlight/HighlightCard0", face);
                AssertSkinnedLikeTheCard(root, "Card1", "Highlight/HighlightCard1", face);
            }
        });
    }

    [Test]
    public void Hand_WinnerGlowIsNotTheBestHandHighlight()
    {
        // the two glows are separate objects: skinning the winner glow must not rewire PlayingCard.highlight
        WithPrefab(HandPath, root =>
        {
            var hand = root.GetComponent<GrabbableHand>();
            Assert.AreNotSame(Find(root, "Highlight/HighlightCard0").gameObject, hand.hole0.highlight);
            Assert.AreNotSame(Find(root, "Highlight/HighlightCard1").gameObject, hand.hole1.highlight);
        });
    }

    [Test]
    public void Hand_WinnerGlowKeepsItsOwnMaterial()
    {
        WithPrefab(HandPath, root =>
        {
            var winner = Find(root, "Highlight/HighlightCard0/Back").GetComponent<SkinnedMeshRenderer>();
            var best = Find(root, "HighlightHand/HighlightCard0/Back").GetComponent<SkinnedMeshRenderer>();
            Assert.AreNotSame(best.sharedMaterial, winner.sharedMaterial);
        });
    }

    [Test]
    public void Hand_HighlightBonesAreThePeekBonesGrabbableHandMoves()
    {
        WithPrefab(HandPath, root =>
        {
            var hand = root.GetComponent<GrabbableHand>();
            var glow0 = Find(root, "HighlightHand/HighlightCard0/Back").GetComponent<SkinnedMeshRenderer>();
            var glow1 = Find(root, "HighlightHand/HighlightCard1/Back").GetComponent<SkinnedMeshRenderer>();
            Assert.IsNotNull(glow0);
            Assert.IsNotNull(glow1);

            foreach (var bone in hand.peekBones0)
                Assert.Contains(bone, glow0.bones, "card 0 peek bone " + bone.name + " unused by its highlight");
            foreach (var bone in hand.peekBones1)
                Assert.Contains(bone, glow1.bones, "card 1 peek bone " + bone.name + " unused by its highlight");
        });
    }

    [Test]
    public void Hand_MovingAPeekBoneMovesTheHighlightGeometry()
    {
        // Behavioural check on top of the reference checks: displace a bone and the highlight's
        // baked mesh must change, like the card's does.
        WithPrefab(HandPath, root =>
        {
            var hand = root.GetComponent<GrabbableHand>();
            var card = Find(root, "Card0/Back").GetComponent<SkinnedMeshRenderer>();
            var glow = Find(root, "HighlightHand/HighlightCard0/Back").GetComponent<SkinnedMeshRenderer>();
            Assert.IsNotNull(glow);

            var before = new Mesh();
            var glowBefore = new Mesh();
            card.BakeMesh(before);
            glow.BakeMesh(glowBefore);

            var bone = hand.peekBones0[hand.peekBones0.Length - 1];
            bone.position += bone.up * 0.02f;

            var after = new Mesh();
            var glowAfter = new Mesh();
            card.BakeMesh(after);
            glow.BakeMesh(glowAfter);

            Assert.AreNotEqual(before.bounds.size, after.bounds.size, "sanity: moving the bone should deform the card");
            Assert.AreNotEqual(glowBefore.bounds.size, glowAfter.bounds.size, "the highlight must deform with it");

            Object.DestroyImmediate(before); Object.DestroyImmediate(after);
            Object.DestroyImmediate(glowBefore); Object.DestroyImmediate(glowAfter);
        });
    }

    [Test]
    public void Hand_PeekRigWiringIsUnchanged()
    {
        // regression: skinning the highlight must not touch the fold rig's own references
        WithPrefab(HandPath, root =>
        {
            var hand = root.GetComponent<GrabbableHand>();
            Assert.AreEqual(hand.peekColumns * hand.peekRows, hand.peekBones0.Length);
            Assert.AreEqual(hand.peekColumns * hand.peekRows, hand.peekBones1.Length);
            Assert.AreSame(Find(root, "Card0"), hand.peekCard0);
            Assert.AreSame(Find(root, "Card1"), hand.peekCard1);
        });
    }
}
