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

// Charity effects play only once the master has accepted a transfer, via a synced per-card count.
public partial class SecurityTests
{
    private AudioPoolPlayer SoundOn(GameObject parent, string name)
    {
        var go = Spawn(name, parent);
        var player = go.AddComponent<AudioPoolPlayer>();
        player.audioSource = go.AddComponent<AudioSource>();
        player.audioClips = new[]
        {
            AudioClip.Create(name + "A", 100, 1, 44100, false),
            AudioClip.Create(name + "B", 100, 1, 44100, false)
        };
        return player;
    }

    // AudioPoolPlayer advances its round-robin index on every play
    private static bool Played(AudioPoolPlayer sound)
    {
        return (int)VrcRuntimeFake.GetPrivate(sound, "currentIndex") != 0;
    }

    private CharityCard CardWithSounds(HoldemAuthority authority)
    {
        var card = authority.charityCards[0];
        card.authority = authority;
        card.successSound = SoundOn(card.gameObject, "Success");
        card.failSound = SoundOn(card.gameObject, "Fail");
        return card;
    }

    private static void Deserialize(HoldemAuthority authority, params int[] donations)
    {
        SetField(authority, "charityDonations", donations);
        authority.OnDeserialization();
    }

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

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

        Assert.AreEqual(1, authority._GetCharityDonations(0));
        Assert.IsTrue(Played(card.successSound), "The master plays its own effects");
    }

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

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

        Assert.AreEqual(0, authority._GetCharityDonations(0));
        Assert.IsFalse(Played(card.successSound));
    }

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

        SendAs(Master, authority, "RequestCharity", VictimId, 1);
        SendAs(Master, authority, "RequestCharity", VictimId, -1);

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

    [Test]
    public void CharityCooldownToleratesNetworkJitter()
    {
        StartAs(MasterId);
        var authority = AuthorityOwnedBy(Master);
        authority.charityCooldownSeconds = 1f;
        authority.charityCooldownToleranceSeconds = 0.25f;
        var sender = BalanceOwnedBy(Master, 100000);
        BalanceOwnedBy(Victim, 0);

        SendAs(Master, authority, "RequestCharity", VictimId, 0);
        vrc.ServerTimeMillis += 800;
        SendAs(Master, authority, "RequestCharity", VictimId, 0);
        Assert.AreEqual(98000, sender.CurrentSyncedBalance, "A request one second apart may arrive a little early");

        vrc.ServerTimeMillis += 500;
        SendAs(Master, authority, "RequestCharity", VictimId, 0);
        Assert.AreEqual(98000, sender.CurrentSyncedBalance, "Requests well inside the cooldown are refused");
    }

    [Test]
    public void ClientsPlayEffectsWhenTheDonationCountGoesUp()
    {
        StartAs(BystanderId);
        var authority = AuthorityOwnedBy(Master);
        var card = CardWithSounds(authority);

        Deserialize(authority, 0);
        Assert.IsFalse(Played(card.successSound));

        Deserialize(authority, 1);
        Assert.IsTrue(Played(card.successSound));
    }

    [Test]
    public void ClientsPlayNoEffectsForOtherUpdates()
    {
        StartAs(BystanderId);
        var authority = AuthorityOwnedBy(Master);
        var card = CardWithSounds(authority);

        Deserialize(authority, 2);
        Deserialize(authority, 2);

        Assert.IsFalse(Played(card.successSound));
    }

    [Test]
    public void LateJoinersDoNotReplayPastDonations()
    {
        StartAs(BystanderId);
        var authority = AuthorityOwnedBy(Master);
        var card = CardWithSounds(authority);

        Deserialize(authority, 5);

        Assert.IsFalse(Played(card.successSound));
    }

    // ---- Sender's card ----

    private CharityCard HeldCard(HoldemAuthority authority)
    {
        var card = CardWithSounds(authority);
        authority.charityCooldownSeconds = 1f;
        SetField(card, "localPlayer", vrc.LocalPlayer);
        SetField(card, "isHeld", true);
        SetField(card, "currentTarget", Victim);
        BalanceOwnedBy(vrc.LocalPlayer, 10000);
        BalanceOwnedBy(Victim, 0);
        return card;
    }

    private static void TryTransfer(CharityCard card)
    {
        var method = typeof(CharityCard).GetMethod("TryTransfer", AnyInstance);
        try
        {
            method.Invoke(card, null);
        }
        catch (TargetInvocationException e)
        {
            System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
        }
    }

    private static bool Awaiting(CharityCard card) { return (bool)GetField(card, "awaitingConfirmation"); }

    [Test]
    public void CardPlaysNothingUntilTheMasterAccepts()
    {
        StartAs(BystanderId);
        var authority = AuthorityOwnedBy(Master);
        var card = HeldCard(authority);

        TryTransfer(card);

        Assert.IsTrue(Awaiting(card));
        Assert.IsFalse(Played(card.successSound));
        Assert.IsFalse(Played(card.failSound));
    }

    [Test]
    public void CardStopsWaitingOnceTheMasterAccepts()
    {
        StartAs(BystanderId);
        var authority = AuthorityOwnedBy(Master);
        var card = HeldCard(authority);
        Deserialize(authority, 0);

        TryTransfer(card);
        Deserialize(authority, 1);
        vrc.ServerTimeMillis += 5000;
        VrcRuntimeFake.InvokeNoArg(card, "Update");

        Assert.IsFalse(Awaiting(card));
        Assert.IsTrue(Played(card.successSound));
        Assert.IsFalse(Played(card.failSound));
    }

    [Test]
    public void CardPlaysTheFailSoundWhenTheMasterRefuses()
    {
        StartAs(BystanderId);
        var authority = AuthorityOwnedBy(Master);
        var card = HeldCard(authority);

        TryTransfer(card);
        vrc.ServerTimeMillis += 1000;
        VrcRuntimeFake.InvokeNoArg(card, "Update");
        Assert.IsFalse(Played(card.failSound), "Still within the confirmation window");

        vrc.ServerTimeMillis += 1000;
        VrcRuntimeFake.InvokeNoArg(card, "Update");
        Assert.IsTrue(Played(card.failSound));
        Assert.IsFalse(Awaiting(card));
    }

    [Test]
    public void CardIgnoresClicksDuringTheCooldown()
    {
        StartAs(BystanderId);
        var authority = AuthorityOwnedBy(Master);
        var card = HeldCard(authority);
        Deserialize(authority, 0);

        TryTransfer(card);
        Deserialize(authority, 1);
        VrcRuntimeFake.InvokeNoArg(card, "Update");
        SetField(card, "currentTarget", Victim); // Update re-targets by hand distance

        vrc.ServerTimeMillis += 900;
        TryTransfer(card);
        Assert.IsFalse(Awaiting(card), "A click inside the cooldown sends nothing");
        Assert.IsFalse(Played(card.failSound), "and stays silent");

        vrc.ServerTimeMillis += 100;
        TryTransfer(card);
        Assert.IsTrue(Awaiting(card));
    }
}
