using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace RenderHeads.Media.AVProVideo
{
	[AddComponentMenu("AVPro Video/Subtitles uGUI", 201)]
	[HelpURL("http://renderheads.com/product/avpro-video/")]
	public class SubtitlesUGUI : MonoBehaviour
	{
		private void Start()
		{
			this.ChangeMediaPlayer(this._mediaPlayer);
		}

		private void OnDestroy()
		{
			this.ChangeMediaPlayer(null);
		}

		public void ChangeMediaPlayer(MediaPlayer newPlayer)
		{
			if (this._mediaPlayer != null)
			{
				this._mediaPlayer.Events.RemoveListener(new UnityAction<MediaPlayer, MediaPlayerEvent.EventType, ErrorCode>(this.OnMediaPlayerEvent));
				this._mediaPlayer = null;
			}
			this._mediaPlayer = newPlayer;
			if (this._mediaPlayer != null)
			{
				this._mediaPlayer.Events.AddListener(new UnityAction<MediaPlayer, MediaPlayerEvent.EventType, ErrorCode>(this.OnMediaPlayerEvent));
			}
		}

		private void OnMediaPlayerEvent(MediaPlayer mp, MediaPlayerEvent.EventType et, ErrorCode errorCode)
		{
			if (et == MediaPlayerEvent.EventType.SubtitleChange)
			{
				string text = this._mediaPlayer.Subtitles.GetSubtitleText();
				text = text.Replace("<font color=", "<color=");
				text = text.Replace("</font>", "</color>");
				text = text.Replace("<u>", string.Empty);
				text = text.Replace("</u>", string.Empty);
				this._text.text = text;
			}
		}

		[SerializeField]
		private MediaPlayer _mediaPlayer;

		[SerializeField]
		private Text _text;
	}
}
