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

// The info panel's biggest-win readout: the amount, and the five winning cards drawn from the atlas.
public class PanelBalanceBestHandTests
{
    private const BindingFlags Priv = BindingFlags.NonPublic | BindingFlags.Instance;

    // Card ids are suit * 13 + (rank - 2); rank 14 is the ace.
    private const int CLUBS = 0, DIAMONDS = 13, HEARTS = 26, SPADES = 39;
    private static int Card(int suit, int rank) { return suit + rank - 2; }

    private static readonly string AmountKey = PlayerBalanceComponent.SaveKeyPrefix + "HoldemBigWinAmountV2";
    private static readonly string HandKey = PlayerBalanceComponent.SaveKeyPrefix + "HoldemBigWinCardsV2";

    private VrcRuntimeFake fake;
    private GameObject root;
    private PlayerBalanceComponent balance;
    private PanelBalance panel;
    private TMP_Text biggestWinText;
    private TMP_Text handNameText;
    private RawImage[] cards;
    private RawImage[] glows;

    private static TMP_Text MakeText(Transform parent, string name)
    {
        var go = new GameObject(name);
        go.transform.SetParent(parent);
        return go.AddComponent<TextMeshProUGUI>();
    }

    private static void Set(object target, string field, object value)
    {
        target.GetType().GetField(field, Priv).SetValue(target, value);
    }

    [SetUp]
    public void SetUp()
    {
        fake = new VrcRuntimeFake();
        fake.Install(1);
        fake.MasterId = 1;

        root = new GameObject("PanelRoot");
        balance = new GameObject("Balance").AddComponent<PlayerBalanceComponent>();
        balance.transform.SetParent(root.transform);
        balance.CurrentSyncedBalance = 10000;
        Set(balance, "bIsReady", true);

        panel = new GameObject("Panel").AddComponent<PanelBalance>();
        panel.transform.SetParent(root.transform);
        biggestWinText = MakeText(panel.transform, "BiggestWin");
        handNameText = MakeText(panel.transform, "HandName");
        cards = new RawImage[5];
        for (int i = 0; i < 5; i++)
        {
            var go = new GameObject("Card_" + i);
            go.transform.SetParent(panel.transform);
            cards[i] = go.AddComponent<RawImage>();
            cards[i].enabled = false;
        }

        Set(panel, "biggestWinText", biggestWinText);
        Set(panel, "bestHandNameText", handNameText);
        Set(panel, "bestHandCards", cards);
        glows = new RawImage[5];
        for (int i = 0; i < 5; i++)
        {
            var go = new GameObject("Glow_" + i);
            go.transform.SetParent(panel.transform);
            glows[i] = go.AddComponent<RawImage>();
            glows[i].enabled = false;
        }
        Set(panel, "bestHandHighlights", glows);
        Set(panel, "balanceComponent", balance);
        Set(panel, "isInitialized", true);
    }

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

    // Trips of nines with J and 7 kickers.
    private static int TripNines()
    {
        return HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 9), Card(DIAMONDS, 9), Card(HEARTS, 9), Card(CLUBS, 11), Card(DIAMONDS, 7), -1, -1);
    }

    private int LitGlows()
    {
        int n = 0;
        foreach (var g in glows) if (g.enabled) n++;
        return n;
    }

    private void ShowHand(int h0, int h1, int f0, int f1, int f2, int turn, int river)
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, HoldemHandEvaluator.PackBestFive(h0, h1, f0, f1, f2, turn, river));
        panel.OnBalanceChanged();
    }

    [Test]
    public void HoleCardsInTheHandGetTheHighlight()
    {
        // Pocket nines make trips with a board nine; both holes play and are the first (trips) cards.
        ShowHand(Card(CLUBS, 9), Card(DIAMONDS, 9), Card(HEARTS, 9), Card(CLUBS, 11), Card(DIAMONDS, 7), -1, -1);

        Assert.AreEqual(2, LitGlows());
        Assert.IsTrue(glows[0].enabled && glows[1].enabled && glows[2].enabled == false);
    }

    [Test]
    public void OnlyTheHoleCardThatPlaysIsHighlightedEvenAfterTheSort()
    {
        // Hole 9 pairs the board 9; hole 3 is not in the best five. The kicker sorts below the pair.
        ShowHand(Card(CLUBS, 9), Card(DIAMONDS, 3), Card(HEARTS, 9), Card(CLUBS, 11), Card(DIAMONDS, 7), Card(SPADES, 5), Card(HEARTS, 2));

        Assert.AreEqual(1, LitGlows());
        // The lit slot is the hole nine, which is one of the pair at the front of the order
        for (int i = 0; i < 5; i++)
        {
            if (glows[i].enabled)
            {
                Assert.AreEqual(7f / 13f, cards[i].uvRect.x, 1e-4f);
                Assert.Less(i, 2);
            }
        }
    }

    [Test]
    public void PlayingTheBoardHighlightsNothing()
    {
        ShowHand(Card(CLUBS, 2), Card(DIAMONDS, 3), Card(HEARTS, 10), Card(HEARTS, 9), Card(HEARTS, 8), Card(HEARTS, 7), Card(HEARTS, 6));

        Assert.AreEqual(0, LitGlows());
        foreach (var c in cards) Assert.IsTrue(c.enabled);
    }

    [Test]
    public void LegacyPackedCardsWithoutHoleBitsHighlightNothing()
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, TripNines() & 0x3FFFFFFF);

        panel.OnBalanceChanged();

        Assert.AreEqual(0, LitGlows());
        foreach (var c in cards) Assert.IsTrue(c.enabled);
    }

    [Test]
    public void StoredWinShowsTheAmountAndFiveCards()
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, TripNines());

        panel.OnBalanceChanged();

        Assert.AreEqual("+2000", biggestWinText.text);
        StringAssert.Contains("Three of a Kind", handNameText.text);
        foreach (var c in cards) Assert.IsTrue(c.enabled, "all five card slots are drawn");
    }

    [Test]
    public void CardsAreOrderedWithTheTripsFirstAndPointAtTheRightAtlasCell()
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, TripNines());

        panel.OnBalanceChanged();

        // First card: a nine. Atlas columns run 2..A, so nine is column 7 of 13.
        Assert.AreEqual(7f / 13f, cards[0].uvRect.x, 1e-4f);
        Assert.AreEqual(1f / 13f, cards[0].uvRect.width, 1e-4f);
        Assert.AreEqual(0.25f, cards[0].uvRect.height, 1e-4f);
        // Nine of hearts is the third row from the top (diamonds, hearts, clubs, spades) -> row 1 -> v = (3 - 1) / 4
        // Whichever nine comes first, its row must match its suit: clubs 2 -> v .25, diamonds 0 -> .75, hearts 1 -> .5
        float v = cards[0].uvRect.y;
        Assert.IsTrue(Mathf.Approximately(v, 0.25f) || Mathf.Approximately(v, 0.75f) || Mathf.Approximately(v, 0.5f));
    }

    [Test]
    public void NoRecordShowsPlaceholdersAndHidesTheCards()
    {
        foreach (var c in cards) c.enabled = true;

        panel.OnBalanceChanged();

        Assert.AreEqual("-", biggestWinText.text);
        Assert.AreEqual("No wins yet", handNameText.text);
        foreach (var c in cards) Assert.IsFalse(c.enabled);
    }

    [Test]
    public void GarbageCardsStillShowTheAmountButNeverDrawCards()
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, 12345); // decodes to repeated card ids

        panel.OnBalanceChanged();

        Assert.AreEqual("+2000", biggestWinText.text);
        foreach (var c in cards) Assert.IsFalse(c.enabled, "cards we can't vouch for stay hidden");
    }

    [Test]
    public void CardIdsAbove51DoNotThrow()
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, 63 | (62 << 6) | (61 << 12) | (60 << 18) | (59 << 24));

        Assert.DoesNotThrow(() => panel.OnBalanceChanged());
        Assert.AreEqual("+2000", biggestWinText.text);
    }

    [Test]
    public void RecordingAWinRefreshesASubscribedPanel()
    {
        fake.IsOwnerOf = go => true;
        balance.SubscribeToBalanceChanges(panel);

        balance.RecordBiggestWin(2000, TripNines());

        Assert.AreEqual("+2000", biggestWinText.text, "the panel must update on its own after a win is recorded");
        foreach (var c in cards) Assert.IsTrue(c.enabled);
    }
}
