using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using UdonSharp;
using UnityEditor;
using UnityEngine;
using VRC.SDKBase;

// Replays what a modded client can send at other players: network events and ownership requests.
public partial class SecurityTests
{
    private const int MasterId = 1, VictimId = 2, AttackerId = 3, BystanderId = 4;
    private const BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
    private static readonly string[] Names = { "", "Master", "Victim", "Attacker", "Bystander" };

    private VrcRuntimeFake vrc;
    private readonly Dictionary<int, VRCPlayerApi> players = new Dictionary<int, VRCPlayerApi>();
    private readonly List<GameObject> spawned = new List<GameObject>();

    private VRCPlayerApi Master { get { return players[MasterId]; } }
    private VRCPlayerApi Victim { get { return players[VictimId]; } }
    private VRCPlayerApi Attacker { get { return players[AttackerId]; } }
    private VRCPlayerApi Bystander { get { return players[BystanderId]; } }

    [TearDown]
    public void TearDown()
    {
        if (vrc != null) vrc.Uninstall();
        vrc = null;
        foreach (var go in spawned) if (go) Object.DestroyImmediate(go);
        spawned.Clear();
        players.Clear();
    }

    // Installs the fake runtime with localId as this client; player 1 is the master.
    private void StartAs(int localId)
    {
        vrc = new VrcRuntimeFake();
        vrc.Install(localId, Names[localId]);
        foreach (int id in new[] { MasterId, VictimId, AttackerId, BystanderId })
        {
            var player = id == localId ? vrc.LocalPlayer : VrcRuntimeFake.MakePlayer(id, Names[id], false);
            vrc.AddPlayer(player);
            players[id] = player;
        }
        vrc.MasterId = MasterId;
    }

    // Delivers an event the way VRChat does. Returns false when VRChat would drop it.
    private bool SendAs(VRCPlayerApi caller, UdonSharpBehaviour target, string eventName, params object[] args)
    {
        if (!IsNetworked(target.GetType())) return false;

        MethodInfo method = null;
        foreach (var m in target.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
        {
            if (m.Name == eventName && m.GetParameters().Length == args.Length) method = m;
        }
        if (method == null) return false;

        bool networkCallable = false;
        foreach (var attribute in method.GetCustomAttributes(true))
        {
            if (attribute.GetType().Name == "NetworkCallableAttribute") networkCallable = true;
        }
        if (!networkCallable && (args.Length > 0 || eventName.StartsWith("_"))) return false;

        var parameters = method.GetParameters();
        var converted = new object[args.Length];
        for (int i = 0; i < args.Length; i++)
        {
            converted[i] = System.Convert.ChangeType(args[i], parameters[i].ParameterType);
        }

        vrc.EnterNetworkCall(caller);
        try
        {
            method.Invoke(target, converted);
        }
        catch (TargetInvocationException e)
        {
            System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
        }
        finally
        {
            vrc.ExitNetworkCall();
        }
        return true;
    }

    internal static bool IsNetworked(System.Type type)
    {
        for (var t = type; t != null && t != typeof(UdonSharpBehaviour); t = t.BaseType)
        {
            var mode = (UdonBehaviourSyncModeAttribute)System.Attribute.GetCustomAttribute(
                t, typeof(UdonBehaviourSyncModeAttribute), false);
            if (mode != null) return mode.behaviourSyncMode != BehaviourSyncMode.None;
        }
        return true;
    }

    private static FieldInfo FindField(System.Type type, string name)
    {
        for (var t = type; t != null; t = t.BaseType)
        {
            var field = t.GetField(name, AnyInstance | BindingFlags.DeclaredOnly);
            if (field != null) return field;
        }
        throw new System.MissingFieldException(type.Name + "." + name);
    }

    private static object GetField(object target, string name) { return FindField(target.GetType(), name).GetValue(target); }
    private static void SetField(object target, string name, object value) { FindField(target.GetType(), name).SetValue(target, value); }

    // Local-only methods may carry a leading underscore to keep them off the network.
    private static void CallEitherName(object target, string name)
    {
        var type = target.GetType();
        var method = type.GetMethod(name, AnyInstance, null, System.Type.EmptyTypes, null)
            ?? type.GetMethod("_" + name, AnyInstance, null, System.Type.EmptyTypes, null);
        Assert.IsNotNull(method, type.Name + "." + name + " not found");
        try
        {
            method.Invoke(target, null);
        }
        catch (TargetInvocationException e)
        {
            System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
        }
    }

    private GameObject Spawn(string name, GameObject parent = null)
    {
        var go = new GameObject(name);
        if (parent != null) go.transform.SetParent(parent.transform);
        else spawned.Add(go);
        return go;
    }

    private PlayerBalanceComponent BalanceOwnedBy(VRCPlayerApi owner, int balance)
    {
        var go = Spawn("Balance_" + owner.displayName);
        var component = go.AddComponent<PlayerBalanceComponent>();
        component.CurrentSyncedBalance = balance;
        SetField(component, "bIsReady", true);
        vrc.Owners[go] = owner;
        vrc.PlayerObjects[owner] = go;
        return component;
    }

    private HoldemGame TableOwnedBy(VRCPlayerApi owner)
    {
        var go = Spawn("Table");
        var game = go.AddComponent<HoldemGame>();
        game.seats = 10;
        game.players = new HoldemPlayer[10];
        for (int i = 0; i < 10; i++)
        {
            var seatGo = Spawn("Seat_" + i, go);
            game.players[i] = seatGo.AddComponent<HoldemPlayer>();
            game.players[i].game = game;
            game.players[i].seatIdx = i;
            vrc.Owners[seatGo] = owner;
        }
        vrc.Owners[go] = owner;
        return game;
    }

    private PlayerBalanceComponent Sit(HoldemGame game, int seat, VRCPlayerApi player, int balance)
    {
        var seatPlayer = game.players[seat];
        vrc.Owners[seatPlayer.gameObject] = player;
        SetField(seatPlayer, "activePlayerId", player.playerId);
        seatPlayer.playerReady = true;
        var component = BalanceOwnedBy(player, balance);
        SetField(seatPlayer, "ActivePlayerBalanceComponent", component);
        return component;
    }

    private GrabbableHand HandAt(HoldemGame game, int seat, VRCPlayerApi owner)
    {
        var go = Spawn("Hand_" + seat, game.gameObject);
        var hand = go.AddComponent<GrabbableHand>();
        hand.player = game.players[seat];
        hand.hole0 = CardUnder(go);
        hand.hole1 = CardUnder(go);
        game.players[seat].grabbableHand = hand;
        vrc.Owners[go] = owner;
        return hand;
    }

    private PlayingCard CardUnder(GameObject parent)
    {
        var card = Spawn("Card", parent).AddComponent<PlayingCard>();
        card.frontRenderer = Spawn("Front", card.gameObject).AddComponent<MeshRenderer>();
        card.frontBlankRenderer = Spawn("Blank", card.gameObject).AddComponent<MeshRenderer>();
        card.backRenderer = Spawn("Back", card.gameObject).AddComponent<MeshRenderer>();
        VrcRuntimeFake.InvokeNoArg(card, "Start");
        return card;
    }

    // ---- Balances and stats ----

    [Test]
    public void AttackerCannotChangeAnotherPlayersBalance()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        SendAs(Attacker, balance, "RequestModifyBalance", 1000000);
        SendAs(Attacker, balance, "RequestModifyBalance", -1000);

        Assert.AreEqual(1000, balance.CurrentSyncedBalance);
    }

    [Test]
    public void MasterCanChangeBalance()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        Assert.IsTrue(SendAs(Master, balance, "RequestModifyBalance", 500));

        Assert.AreEqual(1500, balance.CurrentSyncedBalance);
    }

    [TestCase("RequestRecordFold")]
    [TestCase("RequestRecordWin")]
    [TestCase("RequestRecordLoss")]
    [TestCase("RequestRecordDonation")]
    [TestCase("RequestRecordDonationReceived")]
    [TestCase("RequestRecordHatGiven")]
    [TestCase("RequestRecordHatReceived")]
    [TestCase("RequestRecordHandRoyalFlush")]
    [TestCase("RequestApplyDunceCap")]
    [TestCase("RecordFold")]
    [TestCase("RecordWin")]
    [TestCase("RecordHandRoyalFlush")]
    [TestCase("ApplyDunceCap")]
    [TestCase("_RecordWin")]
    [TestCase("_RecordHatGiven")]
    [TestCase("_RecordStat")]
    [TestCase("RecordStat")]
    public void RetiredStatEventsAreNotNetworkReachable(string eventName)
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        Assert.IsFalse(SendAs(Attacker, balance, eventName), eventName + " reachable by an attacker");
        Assert.IsFalse(SendAs(Master, balance, eventName), eventName + " reachable by the master");

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [TestCase("RequestRecordProfit", -5000)]
    [TestCase("RequestRecordHandClass", 9)]
    [TestCase("RequestRecordStat", PlayerBalanceComponent.STAT_FOLDS)]
    [TestCase("RequestRecordStat", PlayerBalanceComponent.STAT_WINS)]
    [TestCase("RequestRecordStat", PlayerBalanceComponent.STAT_LOSSES)]
    [TestCase("RequestRecordStat", PlayerBalanceComponent.STAT_DONATIONS)]
    [TestCase("RequestRecordStat", PlayerBalanceComponent.STAT_DONATIONS_RECEIVED)]
    [TestCase("RequestRecordStat", PlayerBalanceComponent.STAT_HATS_GIVEN)]
    [TestCase("RequestRecordStat", PlayerBalanceComponent.STAT_HATS_RECEIVED)]
    [TestCase("RequestRecordStat", -1)]
    [TestCase("RequestRecordStat", 7)]
    [TestCase("RequestRecordStat", 999)]
    [TestCase("RequestRecordStat", int.MinValue)]
    [TestCase("RequestRecordStat", int.MaxValue)]
    public void AttackerCannotWriteAnotherPlayersStatValues(string eventName, int value)
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        SendAs(Attacker, balance, eventName, value);

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [Test]
    public void StatEventSentToEveryoneDoesNotWriteBystandersOwnStats()
    {
        StartAs(BystanderId);
        var balance = BalanceOwnedBy(Victim, 1000);

        SendAs(Attacker, balance, "RequestRecordProfit", 12345);
        SendAs(Attacker, balance, "RequestRecordStat", PlayerBalanceComponent.STAT_WINS);
        SendAs(Master, balance, "RequestRecordStat", PlayerBalanceComponent.STAT_WINS);

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [Test]
    public void MasterCanRecordStats()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        SendAs(Master, balance, "RequestRecordStat", PlayerBalanceComponent.STAT_WINS);
        SendAs(Master, balance, "RequestRecordProfit", 250);
        SendAs(Master, balance, "RequestRecordStat", PlayerBalanceComponent.STAT_HATS_GIVEN);
        SendAs(Master, balance, "RequestRecordStat", PlayerBalanceComponent.STAT_HATS_RECEIVED);
        SendAs(Master, balance, "RequestRecordStat", PlayerBalanceComponent.STAT_DONATIONS_RECEIVED);

        Assert.AreEqual(1, balance.GetWins());
        Assert.AreEqual(250, balance.GetProfit());
        Assert.AreEqual(1, balance.GetHatsGiven());
        Assert.AreEqual(1, balance.GetHatsReceived());
        Assert.AreEqual(1, balance.GetDonationsReceived());
    }

    [Test]
    public void MasterCanRecordOnePackedHoldemHandResult()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);
        int mask = PlayerBalanceComponent.HAND_STAT_TRACKED
            | PlayerBalanceComponent.HAND_STAT_VPIP
            | PlayerBalanceComponent.HAND_STAT_PFR
            | PlayerBalanceComponent.HAND_STAT_THREE_BET_OPPORTUNITY
            | PlayerBalanceComponent.HAND_STAT_THREE_BET;

        Assert.IsTrue(SendAs(Master, balance, "RequestRecordHoldemHandStats", mask));

        Assert.AreEqual(1, balance.GetTrackedHands());
        Assert.AreEqual(1, balance.GetVpipHands());
        Assert.AreEqual(1, balance.GetPfrHands());
        Assert.AreEqual(1, balance.GetThreeBetOpportunities());
        Assert.AreEqual(1, balance.GetThreeBets());
        Assert.AreEqual(100f, balance.GetVPIPPercent());
        Assert.AreEqual(100f, balance.GetPFRPercent());
        Assert.AreEqual(100f, balance.GetThreeBetPercent());
    }

    [Test]
    public void PackedHoldemStatsAccumulateBeyondTheBitMask()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        for (int i = 0; i < 5000; i++)
        {
            int mask = PlayerBalanceComponent.HAND_STAT_TRACKED;
            if ((i & 1) == 0) mask |= PlayerBalanceComponent.HAND_STAT_VPIP;
            SendAs(Master, balance, "RequestRecordHoldemHandStats", mask);
        }

        Assert.AreEqual(5000, balance.GetTrackedHands());
        Assert.AreEqual(2500, balance.GetVpipHands());
        Assert.AreEqual(50f, balance.GetVPIPPercent());
    }

    [TestCase(0)]
    [TestCase(1 << 20)]
    [TestCase(PlayerBalanceComponent.HAND_STAT_TRACKED | (1 << 20))]
    [TestCase(PlayerBalanceComponent.HAND_STAT_TRACKED | PlayerBalanceComponent.HAND_STAT_PFR)]
    [TestCase(PlayerBalanceComponent.HAND_STAT_TRACKED | PlayerBalanceComponent.HAND_STAT_THREE_BET)]
    [TestCase(PlayerBalanceComponent.HAND_STAT_TRACKED | PlayerBalanceComponent.HAND_STAT_FOLD_TO_THREE_BET)]
    [TestCase(PlayerBalanceComponent.HAND_STAT_TRACKED | PlayerBalanceComponent.HAND_STAT_CBET)]
    [TestCase(PlayerBalanceComponent.HAND_STAT_TRACKED | PlayerBalanceComponent.HAND_STAT_FOLD_TO_CBET)]
    public void InvalidPackedHoldemStatsAreRejected(int mask)
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        Assert.IsTrue(SendAs(Master, balance, "RequestRecordHoldemHandStats", mask));

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [Test]
    public void AttackerCannotRecordPackedHoldemStats()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        SendAs(Attacker, balance, "RequestRecordHoldemHandStats",
            PlayerBalanceComponent.HAND_STAT_TRACKED | PlayerBalanceComponent.HAND_STAT_VPIP);

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [Test]
    public void CompletedHandStatsFinalizeExactlyOnce()
    {
        StartAs(VictimId);
        var game = TableOwnedBy(Victim);
        var balance = Sit(game, 0, Victim, 1000);
        SetField(game, "pokerStatsHandActive", true);
        SetField(game, "pokerStatsDealtMask", 1);
        var playerIds = (int[])GetField(game, "pokerStatsPlayerIds");
        var masks = (int[])GetField(game, "pokerStatsMasks");
        playerIds[0] = VictimId;
        masks[0] = PlayerBalanceComponent.HAND_STAT_VPIP;
        MethodInfo finalize = typeof(HoldemGame).GetMethod("FinalizePokerStatsHand", AnyInstance);

        finalize.Invoke(game, null);
        finalize.Invoke(game, null);

        Assert.AreEqual(1, balance.GetTrackedHands());
        Assert.AreEqual(1, balance.GetVpipHands());
    }

    [Test]
    public void ResetHandDiscardsStatsWithoutPersistence()
    {
        StartAs(VictimId);
        var game = TableOwnedBy(Victim);
        Sit(game, 0, Victim, 1000);
        SetField(game, "pokerStatsHandActive", true);
        SetField(game, "pokerStatsDealtMask", 1);
        ((int[])GetField(game, "pokerStatsPlayerIds"))[0] = VictimId;
        ((int[])GetField(game, "pokerStatsMasks"))[0] = PlayerBalanceComponent.HAND_STAT_VPIP;

        game._ResetHandState();
        typeof(HoldemGame).GetMethod("FinalizePokerStatsHand", AnyInstance).Invoke(game, null);

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [TestCase(PlayerBalanceComponent.STAT_FOLDS, "S1_HoldemFolds")]
    [TestCase(PlayerBalanceComponent.STAT_WINS, "S1_HoldemWins")]
    [TestCase(PlayerBalanceComponent.STAT_LOSSES, "S1_HoldemLosses")]
    [TestCase(PlayerBalanceComponent.STAT_DONATIONS, "S1_HoldemDonations")]
    [TestCase(PlayerBalanceComponent.STAT_DONATIONS_RECEIVED, "S1_HoldemDonationsReceived")]
    [TestCase(PlayerBalanceComponent.STAT_HATS_GIVEN, "S1_HatsGiven")]
    [TestCase(PlayerBalanceComponent.STAT_HATS_RECEIVED, "S1_HatsReceived")]
    public void StatIdWritesItsOwnPersistenceKey(int statId, string expectedKey)
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        Assert.IsTrue(SendAs(Master, balance, "RequestRecordStat", statId));

        Assert.AreEqual(new[] { "SetInt(" + expectedKey + ", 1)" }, vrc.Writes);
    }

    [TestCase(-1)]
    [TestCase(7)]
    [TestCase(999)]
    [TestCase(int.MinValue)]
    [TestCase(int.MaxValue)]
    public void OutOfRangeStatIdIsRefusedEvenFromTheMaster(int statId)
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        Assert.IsTrue(SendAs(Master, balance, "RequestRecordStat", statId), "event should still be delivered");

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [Test]
    public void LocalRecordWrappersEachWriteTheirOwnStat()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);

        balance._RecordFold();
        balance._RecordWin();
        balance._RecordLoss();
        balance._RecordDonation();
        balance._RecordDonationReceived();
        balance._RecordHatGiven();
        balance._RecordHatReceived();

        Assert.AreEqual(1, balance.GetFolds(), "folds");
        Assert.AreEqual(1, balance.GetWins(), "wins");
        Assert.AreEqual(1, balance.GetLosses(), "losses");
        Assert.AreEqual(1, balance.GetDonation(), "donations");
        Assert.AreEqual(1, balance.GetDonationsReceived(), "donations received");
        Assert.AreEqual(1, balance.GetHatsGiven(), "hats given");
        Assert.AreEqual(1, balance.GetHatsReceived(), "hats received");
    }

    [Test]
    public void StatsIgnoreKeysFromBeforeTheReset()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 1000);
        vrc.SeedInt("HoldemWins", 7);
        vrc.SeedInt("HoldemHandPair", 3);

        Assert.IsTrue(SendAs(Master, balance, "RequestRecordStat", PlayerBalanceComponent.STAT_WINS));

        Assert.AreEqual(1, balance.GetWins());
        Assert.AreEqual(0, balance.GetHandCount("Pair"));
        CollectionAssert.Contains(vrc.Writes, "SetInt(" + PlayerBalanceComponent.SaveKeyPrefix + "HoldemWins, 1)");
    }

    [Test]
    public void WorldUdonChipsSaveKeysUseResetPrefix()
    {
        var root = AssetDatabase.LoadAssetAtPath<GameObject>(HoldemPaths.Asset("parent.prefab"));
        int found = 0;
        foreach (var component in root.GetComponentsInChildren<UdonSharpBehaviour>(true))
        {
            if (component.GetType().Name != "UdonChips") continue;
            found++;
            foreach (var key in new[] { "saveDataKeyMoney", "saveDataKeyLastSaveTime" })
            {
                StringAssert.StartsWith("_UDON_CHIPS/", (string)GetField(component, key), key);
            }
        }
        Assert.AreEqual(1, found, "Expected one UdonChips in parent.prefab");
    }

    [Test]
    public void AttackerCannotResyncBalanceFromUdonChips()
    {
        StartAs(VictimId);
        var balance = BalanceOwnedBy(Victim, 50000);
        var chipsField = typeof(PlayerBalanceComponent).GetField("udonChips");
        var chips = balance.gameObject.AddComponent(chipsField.FieldType);
        chipsField.FieldType.GetField("money").SetValue(chips, 1500f);
        chipsField.SetValue(balance, chips);

        SendAs(Attacker, balance, "OnMoneyChanged");

        Assert.AreEqual(50000, balance.CurrentSyncedBalance);
    }

    [Test]
    public void WorldUdonChipsCannotReceiveNetworkEvents()
    {
        string path = HoldemPaths.Asset("parent.prefab");
        var root = AssetDatabase.LoadAssetAtPath<GameObject>(path);
        Assert.IsNotNull(root, path);

        int found = 0;
        foreach (var component in root.GetComponentsInChildren<Component>(true))
        {
            if (component == null || component.GetType().FullName != "VRC.Udon.UdonBehaviour") continue;
            var source = component.GetType().GetField("programSource", AnyInstance).GetValue(component) as Object;
            if (source == null || (source.name != "UdonChips Udon C# Program Asset" && source.name != "UdonChipsOffline")) continue;

            found++;
            var syncMethod = component.GetType().GetProperty("SyncMethod").GetValue(component);
            Assert.AreEqual(Networking.SyncType.None, syncMethod, source.name + " must not accept network events");
        }
        Assert.AreEqual(2, found, "Expected the UdonChips and UdonChipsOffline behaviours in " + path);
    }

    [Test]
    public void WorldHasOneAuthorityWiredToAllDependentComponents()
    {
        var root = AssetDatabase.LoadAssetAtPath<GameObject>(HoldemPaths.Asset("parent.prefab"));
        var authorities = root.GetComponentsInChildren<HoldemAuthority>(true);
        Assert.AreEqual(1, authorities.Length, "Exactly one HoldemAuthority in the world");

        var cards = root.GetComponentsInChildren<CharityCard>(true);
        Assert.IsNotEmpty(cards);
        CollectionAssert.AreEquivalent(cards, authorities[0].charityCards);
        foreach (var card in cards)
        {
            Assert.AreSame(authorities[0], card.authority, card.name + " must send transfers to the authority");
        }

        CollectionAssert.AreEquivalent(root.GetComponentsInChildren<HoldemGame>(true), authorities[0].tables,
            "The authority unseats flagged players at every table");
        CollectionAssert.AreEquivalent(root.GetComponentsInChildren<HoldemScoreboard>(true), authorities[0].scoreboards);
        CollectionAssert.AreEquivalent(root.GetComponentsInChildren<WheelWelfareComponent>(true), authorities[0].wheels);
        foreach (var hats in root.GetComponentsInChildren<UdonChipsHat.HatManager>(true))
        {
            Assert.AreSame(authorities[0], hats.authority, "Hat manager refuses flagged players");
        }
    }

    // ---- Table ----

    [Test]
    public void AttackerCannotTriggerGiveMoney()
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);
        var balance = Sit(game, 0, Master, 1000);

        SendAs(Attacker, game, "GiveMoney");

        Assert.AreEqual(1000, balance.CurrentSyncedBalance);
    }

    [Test]
    public void AttackerCannotResetGameMidHand()
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.bettingRound = HoldemGame.FLOP;
        game.potContribution[0] = 500;
        game.potContribution[1] = 500;

        SendAs(Attacker, game, "ResetGame");

        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState);
        Assert.AreEqual(500, game.potContribution[0]);
    }

    [Test]
    public void AttackerCannotStartTournament()
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.lastTransitionMillis = vrc.ServerTimeMillis;
        var first = Sit(game, 0, Master, 5000);
        var second = Sit(game, 1, Master, 5000);

        SendAs(Attacker, game, "StartTournament");

        Assert.IsFalse(game.isTournamentActive);
        Assert.AreEqual(5000, first.CurrentSyncedBalance);
        Assert.AreEqual(5000, second.CurrentSyncedBalance);
    }

    [Test]
    public void AttackerCannotCancelTournament()
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);
        game.isTournamentMode = true;
        game.isTournamentActive = true;
        game.lastTransitionMillis = vrc.ServerTimeMillis;
        for (int i = 0; i < 10; i++)
        {
            game.tournamentEliminated[i] = true;
            game.tournamentPlayerNames[i] = "";
        }

        SendAs(Attacker, game, "CancelTournament");

        Assert.IsTrue(game.isTournamentActive);
    }

    [TestCase("ToggleTournamentMode")]
    [TestCase("IncreaseBuyIn")]
    [TestCase("DecreaseBuyIn")]
    [TestCase("IncreaseStartingStack")]
    [TestCase("DecreaseStartingStack")]
    [TestCase("IncreaseBlindTimer")]
    [TestCase("DecreaseBlindTimer")]
    public void AttackerCannotChangeTableSettings(string eventName)
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);
        game.tournamentBuyIn = 5000;
        game.tournamentStartingStack = 20000;
        game.tournamentLevelDurationSeconds = 600f;

        SendAs(Attacker, game, eventName);

        Assert.IsFalse(game.isTournamentMode);
        Assert.AreEqual(5000, game.tournamentBuyIn);
        Assert.AreEqual(20000, game.tournamentStartingStack);
        Assert.AreEqual(600f, game.tournamentLevelDurationSeconds);
    }

    [Test]
    public void MasterCanStillUseTableButtons()
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);
        game.tournamentBuyIn = 1000;

        game._IncreaseBuyIn();

        Assert.AreEqual(1500, game.tournamentBuyIn);
    }

    // ---- Seats ----

    private HoldemPlayer VictimActingAt(out HoldemGame game)
    {
        StartAs(VictimId);
        game = TableOwnedBy(Master);
        Sit(game, 0, Victim, 5000);
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.bettingRound = HoldemGame.PREFLOP;
        game.playerState[0] = HoldemGame.PLAYER_ACTING;
        game.actingSeat = 0;
        game.stacks[0] = 5000;
        game.currentBet = 100;
        game.minimumRaise = 100;
        game.epoch = 7;
        var seat = game.players[0];
        seat.bet = 50;
        seat.committedEpoch = -1;
        return seat;
    }

    [TestCase("UiFoldImmediately")]
    [TestCase("UiConfirmImmediately")]
    [TestCase("UiBetClear")]
    [TestCase("UiBetD10")]
    [TestCase("UiBetP2500")]
    [TestCase("UiBetMinRaise")]
    [TestCase("UiBetCall")]
    public void AttackerCannotActForVictim(string eventName)
    {
        HoldemGame game;
        var seat = VictimActingAt(out game);

        SendAs(Attacker, seat, eventName);

        Assert.AreEqual(50, seat.bet);
        Assert.AreEqual(-1, seat.committedEpoch);
    }

    [TestCase("ReleaseControl")]
    [TestCase("ToggleControl")]
    public void AttackerCannotUnseatVictim(string eventName)
    {
        HoldemGame game;
        var seat = VictimActingAt(out game);

        SendAs(Attacker, seat, eventName);

        Assert.IsTrue(seat.IsSeated());
    }

    [Test]
    public void AttackerCannotTriggerVictimsRebuy()
    {
        StartAs(VictimId);
        var game = TableOwnedBy(Master);
        Sit(game, 0, Victim, 5000);
        game.tableState = HoldemGame.TABLE_IDLE;
        game.wasSeated[0] = true;
        game.stacks[0] = 100;
        var seat = game.players[0];

        SendAs(Attacker, seat, "UiRebuy");

        Assert.AreEqual(0, seat.rebuyVersion);
    }

    [Test]
    public void VictimCanStillFoldLocally()
    {
        HoldemGame game;
        var seat = VictimActingAt(out game);

        seat._UiFoldImmediately();

        Assert.AreEqual(-1, seat.bet);
        Assert.AreEqual(7, seat.committedEpoch);
    }

    // ---- Ownership ----

    [Test]
    public void OccupiedSeatRefusesOwnershipRequests()
    {
        StartAs(VictimId);
        var game = TableOwnedBy(Master);
        Sit(game, 0, Victim, 1000);
        var seat = game.players[0];

        Assert.IsFalse(seat.OnOwnershipRequest(Attacker, Attacker), "Another player must not take an occupied seat");
        Assert.IsFalse(seat.OnOwnershipRequest(Victim, Attacker), "A seat must not be handed to someone else");
        Assert.IsTrue(seat.OnOwnershipRequest(Master, Master), "The master reclaims seats when releasing players");
    }

    [Test]
    public void FreeSeatAcceptsOwnershipRequests()
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);

        Assert.IsTrue(game.players[0].OnOwnershipRequest(Attacker, Attacker));
    }

    [Test]
    public void HandRefusesOwnershipFromAnyoneButItsSeatedPlayer()
    {
        StartAs(VictimId);
        var game = TableOwnedBy(Master);
        Sit(game, 0, Victim, 1000);
        var hand = HandAt(game, 0, Master);

        Assert.IsFalse(hand.OnOwnershipRequest(Attacker, Attacker));
        Assert.IsTrue(hand.OnOwnershipRequest(Victim, Victim));
    }

    [Test]
    public void AuthorityObjectsRefuseOwnershipRequests()
    {
        StartAs(MasterId);
        var game = TableOwnedBy(Master);
        var hats = Spawn("Hats").AddComponent<UdonChipsHat.HatManager>();
        var wheel = Spawn("Wheel").AddComponent<WheelWelfareComponent>();
        var authority = Spawn("Authority").AddComponent<HoldemAuthority>();

        Assert.IsFalse(game.OnOwnershipRequest(Attacker, Attacker), "HoldemGame");
        Assert.IsFalse(hats.OnOwnershipRequest(Attacker, Attacker), "HatManager");
        Assert.IsFalse(wheel.OnOwnershipRequest(Attacker, Attacker), "WheelWelfareComponent");
        Assert.IsFalse(authority.OnOwnershipRequest(Master, Master), "HoldemAuthority");
    }

    // ---- Cards ----

    private HoldemPlayer SeatShowingCards(int handOwnerId, out GrabbableHand hand)
    {
        StartAs(BystanderId);
        var game = TableOwnedBy(Master);
        Sit(game, 0, Victim, 1000);
        hand = HandAt(game, 0, players[handOwnerId]);
        hand.isVisibleToOthers = true;
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.playerState[0] = HoldemGame.PLAYER_PENDING;
        game.holeCards0[0] = 12;
        game.holeCards1[0] = 25;
        return game.players[0];
    }

    [Test]
    public void CardsShownByAnotherPlayerStayHidden()
    {
        GrabbableHand hand;
        var seat = SeatShowingCards(AttackerId, out hand);

        CallEitherName(seat, "UpdateCardDisplay");

        Assert.AreEqual(-1, hand.hole0.id);
        Assert.AreEqual(-1, hand.hole1.id);
    }

    [Test]
    public void CardsShownByTheSeatedPlayerAreRevealed()
    {
        GrabbableHand hand;
        var seat = SeatShowingCards(VictimId, out hand);

        CallEitherName(seat, "UpdateCardDisplay");

        Assert.AreEqual(12, hand.hole0.id);
        Assert.AreEqual(25, hand.hole1.id);
    }

    // ---- Welfare wheel ----

    private WheelWelfareComponent WheelOwnedBy(VRCPlayerApi owner)
    {
        var go = Spawn("Wheel");
        vrc.Owners[go] = owner;
        var wheel = go.AddComponent<WheelWelfareComponent>();
        wheel.Start();
        SetField(wheel, "bHasReceivedPlayerData", true);
        return wheel;
    }

    [Test]
    public void AttackerCannotSpinTheWheelForAVictim()
    {
        StartAs(MasterId);
        var wheel = WheelOwnedBy(Master);

        SendAs(Attacker, wheel, "NotifyPlayerSpin", VictimId);
        SendAs(Attacker, wheel, "RequestSpin", VictimId);

        Assert.AreEqual(EWheelState.None, GetField(wheel, "WheelState"));
    }

    [Test]
    public void AttackerCannotPutVictimOnWelfareCooldown()
    {
        StartAs(VictimId);
        var wheel = WheelOwnedBy(Master);

        SendAs(Attacker, wheel, "NotifyPlayerSpin", VictimId);

        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }

    [Test]
    public void WheelOwnerCanStartASpin()
    {
        StartAs(VictimId);
        var wheel = WheelOwnedBy(Master);

        SendAs(Master, wheel, "NotifyPlayerSpin", VictimId);

        StringAssert.Contains(WelfareComponent.WelfareClaimTimeKeyName, vrc.WriteLog());
    }

    [Test]
    public void EligiblePlayerCanRequestASpin()
    {
        StartAs(MasterId);
        var wheel = WheelOwnedBy(Master);
        BalanceOwnedBy(Bystander, 100);

        Assert.IsTrue(SendAs(Bystander, wheel, "RequestSpin"));

        Assert.AreEqual(EWheelState.Spinning, GetField(wheel, "WheelState"));
    }

    [Test]
    public void PlayerOnWelfareCooldownCannotSpin()
    {
        StartAs(MasterId);
        var wheel = WheelOwnedBy(Master);
        BalanceOwnedBy(Bystander, 100);
        vrc.Store[WelfareComponent.WelfareClaimTimeKeyName] = WelfareComponent.GetTimeNow();

        SendAs(Bystander, wheel, "RequestSpin");

        Assert.AreEqual(EWheelState.None, GetField(wheel, "WheelState"));
    }

    [Test]
    public void PlayerAboveWelfareThresholdCannotSpin()
    {
        StartAs(MasterId);
        var wheel = WheelOwnedBy(Master);
        BalanceOwnedBy(Bystander, 1000000);

        SendAs(Bystander, wheel, "RequestSpin");

        Assert.AreEqual(EWheelState.None, GetField(wheel, "WheelState"));
    }

    // ---- Charity ----

    [Test]
    public void AuthorityWiresEveryConfiguredComponent()
    {
        var authority = Spawn("Authority").AddComponent<HoldemAuthority>();
        var cards = new[]
        {
            Spawn("CharityCardA").AddComponent<CharityCard>(),
            Spawn("CharityCardB").AddComponent<CharityCard>()
        };
        var scoreboards = new[]
        {
            Spawn("ScoreboardA").AddComponent<HoldemScoreboard>(),
            Spawn("ScoreboardB").AddComponent<HoldemScoreboard>()
        };
        var wheels = new[]
        {
            Spawn("WheelA").AddComponent<WheelWelfareComponent>(),
            Spawn("WheelB").AddComponent<WheelWelfareComponent>()
        };
        authority.charityCards = cards;
        authority.scoreboards = scoreboards;
        authority.wheels = wheels;

        VrcRuntimeFake.InvokeNoArg(authority, "Start");

        foreach (var card in cards) Assert.AreSame(authority, card.authority);
        foreach (var scoreboard in scoreboards) Assert.AreSame(authority, scoreboard.authority);
        foreach (var wheel in wheels) Assert.AreSame(authority, wheel.authority);
    }

    private HoldemAuthority AuthorityOwnedBy(VRCPlayerApi owner)
    {
        var go = Spawn("Authority");
        vrc.Owners[go] = owner;
        var authority = go.AddComponent<HoldemAuthority>();
        authority.charityCards = new[] { Spawn("CharityCard").AddComponent<CharityCard>() };
        authority.charityTransferAmount = 1000;
        authority.charityMinimumBalanceRequired = 5000;
        authority.charityCooldownSeconds = 0f;
        authority.charityCooldownToleranceSeconds = 0f;
        VrcRuntimeFake.InvokeNoArg(authority, "Start");
        return authority;
    }

    [Test]
    public void CharityMovesChipsFromTheSender()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        var sender = BalanceOwnedBy(Master, 10000);
        BalanceOwnedBy(Victim, 0);

        SendAs(Master, authority, "RequestCharity", VictimId, 0);

        Assert.AreEqual(9000, sender.CurrentSyncedBalance);
        Assert.AreEqual(1, sender.GetDonation());
    }

    [Test]
    public void CharityCountsAsReceivedByTheTarget()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        BalanceOwnedBy(Bystander, 10000);
        var target = BalanceOwnedBy(Master, 0);

        SendAs(Bystander, authority, "RequestCharity", MasterId, 0);

        Assert.AreEqual(1, target.GetDonationsReceived());
    }

    [Test]
    public void CharityFromAcrossTheWorldIsRefused()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        var sender = BalanceOwnedBy(Master, 10000);
        BalanceOwnedBy(Victim, 0);
        vrc.Positions[MasterId] = new Vector3(50f, 0f, 0f);

        SendAs(Master, authority, "RequestCharity", VictimId, 0);

        Assert.AreEqual(10000, sender.CurrentSyncedBalance);
    }

    [Test]
    public void CharityNeedsTheMinimumBalance()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        var sender = BalanceOwnedBy(Master, 5999);
        BalanceOwnedBy(Victim, 0);

        SendAs(Master, authority, "RequestCharity", VictimId, 0);

        Assert.AreEqual(5999, sender.CurrentSyncedBalance);
    }

    [Test]
    public void CharityIsCappedPerSender()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        authority.charityMaxPerSender = 2;
        var sender = BalanceOwnedBy(Master, 100000);
        BalanceOwnedBy(Victim, 0);

        for (int i = 0; i < 3; i++) SendAs(Master, authority, "RequestCharity", VictimId, 0);

        Assert.AreEqual(98000, sender.CurrentSyncedBalance);
    }

    [Test]
    public void CharityToYourselfIsRefused()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        var sender = BalanceOwnedBy(Master, 10000);

        SendAs(Master, authority, "RequestCharity", MasterId, 0);

        Assert.AreEqual(10000, sender.CurrentSyncedBalance);
    }

    // ---- Hats ----

    private UdonChipsHat.HatManager HatsOwnedBy(VRCPlayerApi owner)
    {
        var go = Spawn("Hats");
        vrc.Owners[go] = owner;
        var hats = go.AddComponent<UdonChipsHat.HatManager>();
        VrcRuntimeFake.InvokeNoArg(hats, "Start");
        return hats;
    }

    // The giver-name parameter goes away once the giver is taken from the caller.
    private bool SendApplyHat(VRCPlayerApi caller, UdonChipsHat.HatManager hats, int target, byte hatType)
    {
        return SendAs(caller, hats, "MasterApplyHat", target, hatType, "Spoofed Giver")
            || SendAs(caller, hats, "MasterApplyHat", target, hatType);
    }

    [Test]
    public void AttackerCannotHatAVictimFromAcrossTheWorld()
    {
        StartAs(MasterId);
        var hats = HatsOwnedBy(Master);
        vrc.Positions[AttackerId] = new Vector3(50f, 0f, 0f);

        SendApplyHat(Attacker, hats, VictimId, 2);

        Assert.IsFalse(hats.PlayerHasHats[VictimId]);
    }

    [Test]
    public void AttackerCannotRemoveAVictimsHatFromAcrossTheWorld()
    {
        StartAs(MasterId);
        var hats = HatsOwnedBy(Master);
        hats.PlayerHasHats[VictimId] = true;
        hats.PlayerHatTypes[VictimId] = 2;
        vrc.Positions[AttackerId] = new Vector3(50f, 0f, 0f);

        SendAs(Attacker, hats, "MasterRemoveHat", VictimId);

        Assert.IsTrue(hats.PlayerHasHats[VictimId]);
    }

    [Test]
    public void NearbyPlayerHatsAVictimUnderTheirOwnName()
    {
        StartAs(MasterId);
        var hats = HatsOwnedBy(Master);
        BalanceOwnedBy(Bystander, 5000);
        vrc.Positions[BystanderId] = new Vector3(0.5f, 0f, 0f);

        Assert.IsTrue(SendApplyHat(Bystander, hats, VictimId, 2));

        Assert.IsTrue(hats.PlayerHasHats[VictimId]);
        Assert.AreEqual("Bystander", hats.PlayerGiverNames[VictimId]);
    }

    [Test]
    public void PlacingAHatChargesTheGiver()
    {
        StartAs(MasterId);
        var hats = HatsOwnedBy(Master);
        var balance = BalanceOwnedBy(Master, 5000);

        SendApplyHat(Master, hats, VictimId, 2);

        Assert.IsTrue(hats.PlayerHasHats[VictimId]);
        Assert.AreEqual(5000 - hats.costToPlaceHat, balance.CurrentSyncedBalance);
    }

    [Test]
    public void PlacingAHatCountsAsGiven()
    {
        StartAs(MasterId);
        var hats = HatsOwnedBy(Master);
        var balance = BalanceOwnedBy(Master, 5000);

        SendApplyHat(Master, hats, VictimId, 2);

        Assert.AreEqual(1, balance.GetHatsGiven());
    }

    [Test]
    public void RestoringYourOwnHatCountsAsNeitherGivenNorReceived()
    {
        StartAs(MasterId);
        var hats = HatsOwnedBy(Master);
        var balance = BalanceOwnedBy(Master, 5000);

        hats.RequestRestoreOwnHat(2, "Alice");

        Assert.IsTrue(hats.PlayerHasHats[MasterId]);
        Assert.AreEqual(0, balance.GetHatsGiven());
        Assert.AreEqual(0, balance.GetHatsReceived());
    }

    [Test]
    public void PlayerWhoCannotAffordAHatCannotPlaceOne()
    {
        StartAs(MasterId);
        var hats = HatsOwnedBy(Master);
        var balance = BalanceOwnedBy(Master, hats.costToPlaceHat - 1);

        SendApplyHat(Master, hats, VictimId, 2);

        Assert.IsFalse(hats.PlayerHasHats[VictimId]);
        Assert.AreEqual(hats.costToPlaceHat - 1, balance.CurrentSyncedBalance);
    }

    [Test]
    public void AttackerCannotCompleteVictimsHatRestore()
    {
        StartAs(VictimId);
        var hats = HatsOwnedBy(Master);

        SendAs(Attacker, hats, "MarkPersistenceRestoreComplete");

        Assert.IsFalse(hats.IsPersistenceRestoreComplete());
        Assert.IsEmpty(vrc.Writes, "Persistence writes: " + vrc.WriteLog());
    }
}
