//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace CommunityServer.Components
{
	/// <summary>
	/// Summary description for VideoModule.
	/// </summary>
	public class VideoModule : ICSModule
	{
		public VideoModule()
		{
		}

		#region ICSModule Members

		public void Init(CSApplication csa, XmlNode node)
		{
			csa.PrePostUpdate += new CSPostEventHandler(csa_PrePostUpdate);
			csa.PreRenderPost += new CSPostEventHandler(csa_PreRenderPost);

            if(node != null)
            {
                XmlAttribute width = node.Attributes["width"];
                if(width != null)
                    _width = Int32.Parse(width.Value);

                XmlAttribute height = node.Attributes["height"];
                if(height != null)
                    _height = Int32.Parse(height.Value);
            }
		}

        private int _width = 300;
        private int _height = 225;

		#endregion

		private void csa_PrePostUpdate(IContent content, CSPostEventArgs e)
		{
			Post post = content as Post;

			if(post != null && e.State != ObjectState.Delete)
			{
				if(post.HasVideo)
				{
					TextToken token = new TextToken();
					token.Token = "Video";

					if(!Regex.IsMatch(post.FormattedBody, token.Pattern, RegexOptions.IgnoreCase))
						post.FormattedBody += "[Video]";
				}
			}
		}

		private void csa_PreRenderPost(IContent content, CSPostEventArgs e)
		{
			Post post = content as Post;

            if(post == null || !post.HasVideo)
                return;

			foreach(TextPart tp in e.TextParts)
			{
				if(tp.Name.ToLower() == "video")
				{
					string videoUI = CreateInlineVideoUI(post, e.Target);
					content.FormattedBody = tp.Replace(content.FormattedBody, videoUI);
				}
			}
		}

		private string CreateInlineVideoUI(Post post, PostTarget target)
		{
			CSContext context = CSContext.Current;

			int height = post.VideoHeight < 0 ? _height : post.VideoHeight;
			int width = post.VideoWidth < 0 ? _width : post.VideoWidth;

			string details = string.Format(ResourceManager.GetString("PostDisplay_VideoPost_Details"), Globals.HtmlEncode(post.VideoFileFormat), Globals.HtmlEncode(post.VideoDuration));
			string altRendering = string.Format("<a href=\"{0}\"><img src=\"{1}\" border = \"0\" width=\"{4}\" height=\"{5}\"></a><br /><a href = \"{0}\">{2}</a><br />{3}",post.VideoUrl,post.VideoImageUrl,ResourceManager.GetString("PostDisplay_VideoPost_AlternateText"),details,width,height);

			StringBuilder ui = new StringBuilder();
			ui.Append("<p align=\"center\">");

			if(context.IsWebRequest && target == PostTarget.Web)
			{
				switch (post.VideoFileFormat.ToUpper())
				{
					case "MOV":

						ui.Append("<object ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", (height + 16).ToString());
						AddProperty(ui, "classid", "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B");
						AddProperty(ui, "codebase", "http://www.apple.com/qtactivex/qtplugin.cab");
						ui.Append(">");

						AddParameter(ui, "src", post.VideoUrl);
						AddParameter(ui, "autoplay", "false");
						AddParameter(ui, "controller", "true");
						AddParameter(ui, "scale", "tofit");
						
						ui.Append("<embed ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", (height + 16).ToString());
						AddProperty(ui, "src", post.VideoUrl);
						AddProperty(ui, "controller", "true");
						AddProperty(ui, "autoplay", "false");
						AddProperty(ui, "type", "video/quicktime");
						AddProperty(ui, "scale", "tofit");
						ui.Append(">");

						ui.Append("<noembed>");
						ui.Append(altRendering);
						ui.Append("</noembed>");

						ui.Append("</embed>");
						ui.Append("</object>");

						break;

					case "RA":
					case "RAM":
					case "RPM":
					case "RV":

						ui.Append("<object id=\"RVOCX\" ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", height.ToString());
						AddProperty(ui, "classid", "clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA");
						ui.Append(">");

						AddParameter(ui, "src", post.VideoUrl);
						AddParameter(ui, "controls", "ImageWindow");
						AddParameter(ui, "console", "one");
						AddParameter(ui, "autostart", "false");
						
						ui.Append("<embed ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", height.ToString());
						AddProperty(ui, "src", post.VideoUrl);
						AddProperty(ui, "console", "one");
						AddProperty(ui, "controls", "ImageWindow");

						AddProperty(ui, "autostart", "false");
						AddProperty(ui, "type", "audio/x-pn-realaudio-plugin");
						ui.Append(">");

						ui.Append("<noembed>");
						ui.Append(altRendering);
						ui.Append("</noembed>");

						ui.Append("</embed>");
						ui.Append("</object>");

						ui.Append("<br /><object id=\"RVOCX\" ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", "32");
						AddProperty(ui, "classid", "clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA");
						ui.Append(">");

						AddParameter(ui, "src", post.VideoUrl);
						AddParameter(ui, "controls", "ControlPanel");
						AddParameter(ui, "autostart", "false");
						AddParameter(ui, "console", "one");
						
						ui.Append("<embed ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", "32");
						AddProperty(ui, "src", post.VideoUrl);
						AddProperty(ui, "controls", "ControlPanel");
						AddProperty(ui, "autostart", "false");
						AddProperty(ui, "type", "audio/x-pn-realaudio-plugin");
						AddProperty(ui, "console", "one");
						ui.Append(">");

						ui.Append("</embed>");
						ui.Append("</object>");
						
						break;

					case "SWF":

						ui.Append("<object ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", height.ToString());
						AddProperty(ui, "classid", "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000");
						AddProperty(ui, "codebase", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab");
						ui.Append(">");

						AddParameter(ui, "movie", post.VideoUrl);
						AddParameter(ui, "quality", "high");
						
						ui.Append("<embed ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", height.ToString());
						AddProperty(ui, "src", post.VideoUrl);
						AddProperty(ui, "quality", "high");
						AddProperty(ui, "type", "application/x-shockwave-flash");
						AddProperty(ui, "pluginspage", "http://www.macromedia.com/go/getflashplayer");
						ui.Append(">");

						ui.Append("<noembed>");
						ui.Append(altRendering);
						ui.Append("</noembed>");

						ui.Append("</embed>");
						ui.Append("</object>");

						break;

					default:

						ui.Append("<object ");
						AddProperty(ui, "classid", "CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", height.ToString());
						ui.Append(">");

						AddParameter(ui, "SendPlayStateChangeEvents", "True");
						AddParameter(ui, "AutoStart", "False");
						AddParameter(ui, "enabled", "True");
						AddParameter(ui, "uiMode", "full");
						AddParameter(ui, "PlayCount", "1");
						AddParameter(ui, "URL", post.VideoUrl);
						AddParameter(ui, "autoplay", "false");
						AddParameter(ui, "controller", "true");
						AddParameter(ui, "scale", "tofit");
						AddParameter(ui, "type", "application/x-oleobject");

						ui.Append("<embed ");
						AddProperty(ui, "width", width.ToString());
						AddProperty(ui, "height", height.ToString());
						AddProperty(ui, "showstatusbar", "0");
						AddProperty(ui, "showcontrols", "1");
						AddProperty(ui, "showdisplay", "0");
						AddProperty(ui, "autostart", "0");
						AddProperty(ui, "src", post.VideoUrl);
						AddProperty(ui, "controller", "true");
						AddProperty(ui, "autoplay", "false");
						AddProperty(ui, "scale", "tofit");
						AddProperty(ui, "type", DetermineType(post.VideoFileFormat.ToUpper()));
						ui.Append(">");

						ui.Append("<noembed>");
						ui.Append(altRendering);
						ui.Append("</noembed>");

						ui.Append("</embed>");
						ui.Append("</object>");

						break;
				}
			}
			else
			{
				ui.Append(altRendering);
			}

			ui.Append("</p>");
			return ui.ToString();
		}

		private void AddProperty(StringBuilder sb, string name, string value)
		{
			sb.Append(name);
			sb.Append("=\"");
			sb.Append(value);
			sb.Append("\" ");
		}

		private void AddParameter(StringBuilder sb, string name, string value)
		{
			sb.Append("<param name=\"");
			sb.Append(name);
			sb.Append("\" value=\"");
			sb.Append(value);
			sb.Append("\" />");
		}

		private string DetermineType(string ext)
		{
			switch (ext)
			{
				case "ASF":
				case "ASX":
				case "WVX":
				case "WM":
				case "WMX":
				case "WMV":
					return "video/x-ms-" + ext.ToLower();
				
				case "AVI":
					return "video/avi";

				case "MPG":
					return "video/mpeg";

				case "MP4":
					return "video/mpeg4";

				default:
					return "application/x-mplayer2";
			}
		}
	}
}
