﻿using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;

namespace CustomTimeline
{
	[TrackColor(0.8f, 1.0f, 0.6f)]
    [TrackClipType(typeof(SlowMotionClip))]
    [TrackBindingType(typeof(TimelineSpeedController))]
    public class SlowMotionTrack : TrackAsset
    {
		public override Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount)
		{
			var scriptPlayable = ScriptPlayable<SlowMotionMixerBehaviour>.Create(graph, inputCount);

			SlowMotionMixerBehaviour b = scriptPlayable.GetBehaviour();
			b.markerClips = new System.Collections.Generic.Dictionary<string, double>();

            //This foreach will rename clips based on what they do, and collect the markers and put them into a dictionary
            //Since this happens when you enter Preview or Play mode, the object holding the Timeline must be enabled or you won't see any change in names
            foreach (var c in GetClips())
			{
				SlowMotionClip clip = (SlowMotionClip)c.asset;
				string clipName = c.displayName;

				switch (clip.action)
				{
					case SlowMotionBehaviour.SlowMotionAction.SlowDownAndJumpToMarker:
						clipName = "↪  " + clip.markerToJumpTo.ToString();
                        break;
					case SlowMotionBehaviour.SlowMotionAction.Marker:
						clipName = "● " + clip.markerLabel.ToString();

						//Insert the marker clip into the Dictionary of markers
						if (!b.markerClips.ContainsKey(clip.markerLabel)) //happens when you duplicate a clip and it has the same markerLabel
						{
							b.markerClips.Add(clip.markerLabel, (double)c.start);
                        }
						break;
                    case SlowMotionBehaviour.SlowMotionAction.ContinuousSlowing:
                        clipName = "✯¸.••✿  " + clip.markerLabel + "  ✿••.¸✯ ";
                        break;
                }

				c.displayName = clipName;
			}

			return scriptPlayable;
		}







		public override void GatherProperties(PlayableDirector director, IPropertyCollector driver)
        {
#if UNITY_EDITOR
            TimelineSpeedController trackBinding = director.GetGenericBinding(this) as TimelineSpeedController;
            if (trackBinding == null)
                return;

            var serializedObject = new UnityEditor.SerializedObject(trackBinding);
            var iterator = serializedObject.GetIterator();
            while (iterator.NextVisible(true))
            {
                if (iterator.hasVisibleChildren)
                    continue;

                driver.AddFromName<TimelineSpeedController>(trackBinding.gameObject, iterator.propertyPath);
            }
#endif
            base.GatherProperties(director, driver);
        }
    }
}