/* 
*   NatCorder
*   Copyright (c) 2020 Yusuf Olokoba.
*/

namespace NatSuite.Recorders.Clocks {

    using System.Runtime.CompilerServices;
    using Internal;

    /// <summary>
    /// Clock that produces timestamps spaced at a fixed interval.
    /// This clock is useful for enforcing a fixed framerate in a recording.
    /// </summary>
    [Doc(@"FixedIntervalClock")]
    public sealed class FixedIntervalClock : IClock {

        /// <summary>
        /// Interval between consecutive timestamps generated by the clock in seconds.
        /// </summary>
        [Doc(@"FixedIntervalClockInterval")]
        public double interval { get; set; }

        /// <summary>
        /// Current timestamp in nanoseconds.
        /// The very first value reported by this property will always be zero.
        /// </summary>
        [Doc(@"Timestamp")]
        public long timestamp {
            [MethodImpl(MethodImplOptions.Synchronized)]
            get => (long)((autoTick ? ticks++ : ticks) * interval * 1e+9);
        }

        /// <summary>
        /// Create a fixed interval clock for a given framerate.
        /// </summary>
        /// <param name="framerate">Desired framerate for clock's timestamps.</param>
        /// <param name="autoTick">Optional. If true, the clock will tick when its `Timestamp` is accessed.</param>
        [Doc(@"FixedIntervalClockCtorFramerate")]
        public FixedIntervalClock (int framerate, bool autoTick = true) : this(1.0 / framerate, autoTick) { }
        
        /// <summary>
        /// Create a fixed interval clock with a given timestamp interval.
        /// </summary>
        /// <param name="interval">Interval between consecutive timestamps in seconds.</param>
        /// <param name="autoTick">Optional. If true, the clock will tick when its `Timestamp` is accessed.</param>
        [Doc(@"FixedIntervalClockCtorInterval")]
        public FixedIntervalClock (double interval, bool autoTick = true) {
            this.interval = interval;
            this.ticks = 0;
            this.autoTick = autoTick;
        }

        /// <summary>
        /// Advance the clock by its time interval.
        /// </summary>
        [MethodImpl(MethodImplOptions.Synchronized), Doc(@"FixedIntervalClockTick")]
        public void Tick () => ticks++;

        private readonly bool autoTick;
        private int ticks;
    }
}