using System;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

namespace CustomTimeline
{
    public class TimelineSpeedMixerBehaviour : PlayableBehaviour
    {
        TimelineSpeedController trackBinding;
        readonly float defaultTimeScale = 1f;

        public override void ProcessFrame(Playable playable, FrameData info, object playerData)
        {
            trackBinding = playerData as TimelineSpeedController;
            if (!trackBinding)
                return;

            int inputCount = playable.GetInputCount();

            float mixedTimeScale = 0f;
            float totalWeight = 0f;
            int currentInputCount = 0;

            for (int i = 0; i < inputCount; i++)
            {
                float inputWeight = playable.GetInputWeight(i);
                ScriptPlayable<TimelineSpeedBehaviour> playableInput = (ScriptPlayable<TimelineSpeedBehaviour>)playable.GetInput(i);
                TimelineSpeedBehaviour input = playableInput.GetBehaviour();

                if (inputWeight > 0f)
                    currentInputCount++;

                totalWeight += inputWeight;


                mixedTimeScale += inputWeight * input.timeSpeed;
            }
            trackBinding.speed = mixedTimeScale + defaultTimeScale * (1f - totalWeight);

            if (currentInputCount == 0)
                trackBinding.speed = defaultTimeScale;
        }

        public override void OnGraphStop(Playable playable)
        {
            trackBinding.speed = defaultTimeScale;
        }
    }
}