using Coherence.Core;
using Coherence.Toolkit;

namespace Dissonance.Integrations.Coherence
{
    /// <summary>
    /// Timestamps voice packets on coherence's network clock instead of the local system clock.
    /// </summary>
    /// <remarks>
    /// The stale-audio check compares a timestamp written by the sender against one read by the
    /// receiver. Taken from <see cref="System.DateTime.UtcNow"/> that comparison measures how far
    /// apart the two machines have their system clocks set, so a player whose clock runs a few
    /// seconds ahead of everyone else's discards every unreliable packet that reaches them and
    /// hears nobody. Network time is served by the Replication Server and reads the same on every
    /// client, so the difference measures transit time, which is what the check is for.
    /// </remarks>
    internal static class VoiceClock
    {
        /// <summary>Stamp used when network time is unavailable. Packets carrying it are never stale.</summary>
        public const long UnknownFrame = long.MinValue;

        /// <summary>Current network simulation frame of <paramref name="bridge"/>, or <see cref="UnknownFrame"/>.</summary>
        public static long Stamp(CoherenceBridge bridge) =>
            TryGetFrame(bridge, out var frame) ? frame : UnknownFrame;

        /// <summary>Whether a packet stamped at <paramref name="sendFrame"/> is older than <paramref name="staleSeconds"/>.</summary>
        public static bool IsStale(CoherenceBridge bridge, long sendFrame, float staleSeconds)
        {
            if (sendFrame == UnknownFrame || !TryGetFrame(bridge, out var receiveFrame))
            {
                return false;
            }

            // A client's simulation frame runs ahead of the server's by its own ping estimate, so a
            // sender on a worse connection stamps frames the receiver has already passed and one on a
            // better connection stamps frames the receiver has not reached yet. Only positive age can
            // be stale; a negative difference is that normal spread, not a packet from the future.
            return (receiveFrame - sendFrame) * NetworkTime.timeStep > staleSeconds;
        }

        private static bool TryGetFrame(CoherenceBridge bridge, out long frame)
        {
            var networkTime = bridge ? bridge.NetworkTime : null;
            if (networkTime is not { IsTimeSynced: true })
            {
                frame = UnknownFrame;
                return false;
            }

            frame = networkTime.ClientSimulationFrame;
            return true;
        }
    }
}
