using NUnit.Framework;
using UnityEngine;
using VRC.SDKBase;

// The master catches balances that don't add up, then unseats and flags those players.
public partial class SecurityTests
{
    private const int GraceMillis = 60 * 1000;

    private HoldemAuthority LedgerAuthority()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        SetField(authority, "ledgerGraceSeconds", GraceMillis / 1000f);
        SetField(authority, "maxPlausibleBalance", 10000000);
        SetField(authority, "welfareAllowance", 100);
        SetField(authority, "welfareIntervalMinutes", 5);
        return authority;
    }

    private void CheckLater(HoldemAuthority authority, int millis)
    {
        vrc.ServerTimeMillis += millis;
        CallEitherName(authority, "CheckPlayers");
    }

    private bool IsFlagged(HoldemAuthority authority, string name)
    {
        var method = typeof(HoldemAuthority).GetMethod("IsFlagged");
        Assert.IsNotNull(method, "HoldemAuthority.IsFlagged");
        return (bool)method.Invoke(authority, new object[] { name });
    }

    [Test]
    public void IgnoredLossIsFlagged()
    {
        var authority = LedgerAuthority();
        var victim = BalanceOwnedBy(Victim, 5000);
        CheckLater(authority, 0);

        // The master charges a loss; a modded client never applies it
        victim.ModifyBalance(-1000);
        CheckLater(authority, GraceMillis + 1000);
        CheckLater(authority, 5000);

        Assert.IsTrue(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void AppliedLossIsNotFlagged()
    {
        var authority = LedgerAuthority();
        var victim = BalanceOwnedBy(Victim, 5000);
        CheckLater(authority, 0);

        victim.ModifyBalance(-1000);
        victim.CurrentSyncedBalance = 4000;
        CheckLater(authority, GraceMillis + 1000);
        CheckLater(authority, 5000);

        Assert.IsFalse(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void LossStillInFlightIsNotFlagged()
    {
        var authority = LedgerAuthority();
        var victim = BalanceOwnedBy(Victim, 5000);
        CheckLater(authority, 0);

        victim.ModifyBalance(-1000);
        CheckLater(authority, 1000);
        CheckLater(authority, 1000);

        Assert.IsFalse(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void BalanceInflatedMidSessionIsFlagged()
    {
        var authority = LedgerAuthority();
        var victim = BalanceOwnedBy(Victim, 5000);
        CheckLater(authority, 0);

        victim.CurrentSyncedBalance = 900000;
        CheckLater(authority, 5000);
        CheckLater(authority, 5000);

        Assert.IsTrue(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void WelfareSizedCreditIsNotFlagged()
    {
        var authority = LedgerAuthority();
        var victim = BalanceOwnedBy(Victim, 500);
        CheckLater(authority, 0);

        victim.CurrentSyncedBalance = 600;
        CheckLater(authority, 5000);
        CheckLater(authority, 5000);

        Assert.IsFalse(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void ImpossibleBalanceIsFlaggedOnSight()
    {
        var authority = LedgerAuthority();
        BalanceOwnedBy(Victim, 50000000);

        CheckLater(authority, 0);

        Assert.IsTrue(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void MasterIsNeverFlagged()
    {
        var authority = LedgerAuthority();
        BalanceOwnedBy(Master, 50000000);

        CheckLater(authority, 0);

        Assert.IsFalse(IsFlagged(authority, "Master"));
    }

    [Test]
    public void FlagsAreKeptInSyncedState()
    {
        var authority = LedgerAuthority();
        BalanceOwnedBy(Victim, 50000000);

        CheckLater(authority, 0);

        var names = (string[])GetField(authority, "flaggedNames");
        CollectionAssert.Contains(names, "Victim");
    }

    [Test]
    public void FlaggedPlayerIsUnseated()
    {
        var authority = LedgerAuthority();
        var game = TableOwnedBy(Master);
        SetField(authority, "tables", new[] { game });
        Sit(game, 0, Victim, 50000000);

        CheckLater(authority, 0);

        Assert.IsFalse(game.players[0].IsSeated());
    }

    [Test]
    public void FlaggedPlayerCannotSendCharity()
    {
        var authority = LedgerAuthority();
        BalanceOwnedBy(Victim, 50000000);
        BalanceOwnedBy(Bystander, 0);
        CheckLater(authority, 0);

        SendAs(Victim, authority, "RequestCharity", BystanderId, 0);

        var sent = GetField(authority, "charitySentCount");
        Assert.AreEqual(0, sent.GetType().GetProperty("Count").GetValue(sent), "A flagged sender's transfer must be refused");
    }

    [Test]
    public void OnlyTheMasterClearsFlagsLocally()
    {
        var authority = LedgerAuthority();
        BalanceOwnedBy(Victim, 50000000);
        CheckLater(authority, 0);

        SendAs(Attacker, authority, "ClearFlags");
        Assert.IsTrue(IsFlagged(authority, "Victim"), "A network event must not clear flags");

        CallEitherName(authority, "ClearFlags");
        Assert.IsFalse(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void TableButtonClearsFlagsOnlyLocally()
    {
        var authority = LedgerAuthority();
        var game = TableOwnedBy(Master);
        game.authority = authority;
        BalanceOwnedBy(Victim, 50000000);
        CheckLater(authority, 0);

        SendAs(Attacker, game, "ClearFlags");
        Assert.IsTrue(IsFlagged(authority, "Victim"), "A network event must not clear flags");

        game._ClearFlags();
        Assert.IsFalse(IsFlagged(authority, "Victim"));
    }

    [Test]
    public void TableMasterPanelHasAClearFlagsButton()
    {
        var table = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(HoldemPaths.Asset("Prefabs/HoldemGame.prefab"));
        var button = table.transform.Find("GameMenus/DebugCanvas/MasterDebug/ClearFlagsButton");
        Assert.IsNotNull(button, "ClearFlagsButton");

        var onClick = button.GetComponent<UnityEngine.UI.Button>().onClick;
        Assert.AreEqual("SendCustomEvent", onClick.GetPersistentMethodName(0));
        var target = onClick.GetPersistentTarget(0) as Component;
        Assert.IsNotNull(target);
        Assert.IsNotNull(target.GetComponent<HoldemGame>(), "The button must call the table");

        var so = new UnityEditor.SerializedObject(button.GetComponent<UnityEngine.UI.Button>());
        Assert.AreEqual("_ClearFlags",
            so.FindProperty("m_OnClick.m_PersistentCalls.m_Calls.Array.data[0].m_Arguments.m_StringArgument").stringValue);
    }

    [Test]
    public void FlaggedPlayerCannotSitDown()
    {
        StartAs(VictimId);
        var authority = AuthorityOwnedBy(Master);
        SetField(authority, "flaggedNames", new[] { "Victim" });
        var game = TableOwnedBy(Master);
        game.authority = authority;
        BalanceOwnedBy(Victim, 1000);

        game.players[0]._ToggleControl();

        Assert.IsFalse(game.players[0].IsSeated());
    }
}
