/**********************************************************************************
* Blueprint Reality Inc. CONFIDENTIAL
* 2020 Blueprint Reality Inc.
* All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains, the property of
* Blueprint Reality Inc. and its suppliers, if any.  The intellectual and
* technical concepts contained herein are proprietary to Blueprint Reality Inc.
* and its suppliers and may be covered by Patents, pending patents, and are
* protected by trade secret or copyright law.
*
* Dissemination of this information or reproduction of this material is strictly
* forbidden unless prior written permission is obtained from Blueprint Reality Inc.
***********************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace BlueprintReality.MixCast
{
    [Serializable]
    public class FrameTimer
    {
        public const ulong TicksPerSecond = 1000 * 10000;

        public bool IsStarted { get; protected set; }

        public ulong LastFrameIndex { get; protected set; }
        public ulong LastUpdateTime { get; protected set; }
        public ulong LastIdealTime { get; protected set; }

        public float FrameRate { get; protected set; }

        ulong startTimestamp;

        public void Start(float frameRate)
        {
            FrameRate = frameRate;

			startTimestamp = MixCastTimestamp.Get();

            LastUpdateTime = startTimestamp;
            LastFrameIndex = 0;
            LastIdealTime = startTimestamp;

            IsStarted = true;
        }

        public void Update()
        {
			LastUpdateTime = MixCastTimestamp.Get();
            LastFrameIndex = GetFrameIndexForTimestamp(LastUpdateTime - startTimestamp, FrameRate);
            LastIdealTime = GetIdealTimestampForFrameIndex(LastFrameIndex, FrameRate) + startTimestamp;
        }

        public static ulong GetFrameIndexForTimestamp(ulong durationTicks, float framerate)
        {
            ulong extraDuration = (ulong)(TicksPerSecond / 2 / framerate);
            return (ulong)((double)framerate * (durationTicks + extraDuration) / TicksPerSecond);
        }
        public static ulong GetIdealTimestampForFrameIndex(ulong frameIndex, float framerate)
        {
            return (ulong)((double)frameIndex * TicksPerSecond / framerate);
        }

        public static ulong GetMidnightRelativeFrameIndex(ulong timestamp, float framerate)
        {
            const ulong TicksPerDay = 24L * 60 * 60 * 1000 * 10000;
            ulong ticksPerFrame = (ulong)(TicksPerSecond / (double)framerate);
            return GetFrameIndexForTimestamp((timestamp - timestamp % ticksPerFrame) % TicksPerDay, framerate);
        }
    }
}
