using System;
using UnityEngine;

namespace RenderHeads.Media.AVProVideo.Demos
{
	public class PlaybackSync : MonoBehaviour
	{
		private void Start()
		{
			for (int i = 0; i < this._slavePlayers.Length; i++)
			{
				this._slavePlayers[i].m_Muted = true;
				if (this._matchVideo)
				{
					this._slavePlayers[i].OpenVideoFromFile(this._masterPlayer.m_VideoLocation, this._masterPlayer.m_VideoPath, false);
				}
			}
		}

		private void LateUpdate()
		{
			if (this._state == PlaybackSync.State.Loading && this.IsAllVideosLoaded())
			{
				this._masterPlayer.Play();
				for (int i = 0; i < this._slavePlayers.Length; i++)
				{
					this._slavePlayers[i].Play();
				}
				this._state = PlaybackSync.State.Playing;
			}
			if (this._state == PlaybackSync.State.Finished)
			{
				Debug.Log("Do Something");
			}
			else if (this._state == PlaybackSync.State.Playing)
			{
				if (this._masterPlayer.Control.IsPlaying())
				{
					float currentTimeMs = this._masterPlayer.Control.GetCurrentTimeMs();
					for (int j = 0; j < this._slavePlayers.Length; j++)
					{
						MediaPlayer mediaPlayer = this._slavePlayers[j];
						float currentTimeMs2 = mediaPlayer.Control.GetCurrentTimeMs();
						float num = Mathf.Abs(currentTimeMs - currentTimeMs2);
						if (num > this._toleranceMs)
						{
							mediaPlayer.Control.SeekFast(currentTimeMs + this._toleranceMs * 0.5f);
							if (mediaPlayer.Control.IsPaused())
							{
								mediaPlayer.Play();
							}
						}
					}
				}
				else
				{
					for (int k = 0; k < this._slavePlayers.Length; k++)
					{
						MediaPlayer mediaPlayer2 = this._slavePlayers[k];
						mediaPlayer2.Pause();
					}
				}
				if (PlaybackSync.IsPlaybackFinished(this._masterPlayer))
				{
					this._state = PlaybackSync.State.Finished;
				}
			}
		}

		private bool IsAllVideosLoaded()
		{
			bool result = false;
			if (PlaybackSync.IsVideoLoaded(this._masterPlayer))
			{
				result = true;
				for (int i = 0; i < this._slavePlayers.Length; i++)
				{
					if (!PlaybackSync.IsVideoLoaded(this._slavePlayers[i]))
					{
						result = false;
						break;
					}
				}
			}
			return result;
		}

		private static bool IsVideoLoaded(MediaPlayer player)
		{
			return player != null && player.Control != null && player.Control.HasMetaData() && player.Control.CanPlay() && player.TextureProducer.GetTextureFrameCount() > 0;
		}

		private static bool IsPlaybackFinished(MediaPlayer player)
		{
			bool result = false;
			if (player != null && player.Control != null && player.Control.IsFinished())
			{
				result = true;
			}
			return result;
		}

		public MediaPlayer _masterPlayer;

		public MediaPlayer[] _slavePlayers;

		public float _toleranceMs = 30f;

		public bool _matchVideo = true;

		public bool _muteSlaves = true;

		private PlaybackSync.State _state;

		private enum State
		{
			Loading,
			Playing,
			Finished
		}
	}
}
