//------------------------------------------------------------------------------
// <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 PollRenderingModule : ICSModule
	{
		#region ICSModule Members

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

		#endregion

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

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

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

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

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

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

		private string ProcessInlinePoll(Post post, PostTarget target)
		{
			if (target != PostTarget.Web && target != PostTarget.Unknown)
			{
				return ResourceManager.GetString("PollModule_VisitSiteToAccessPoll");
			}

			StringBuilder ui = new StringBuilder();
			PollSummary poll = Polls.GetPoll(post);
			CSContext cntx = CSContext.Current;
			bool hasVoted = poll.HasVoted(cntx.User.UserID);
			int totalVotes = 0;
			double percent;
			bool canVote = Permissions.ValidatePermissions(post.Section, Permission.Vote, cntx.User);
			
			#region Handle Voting Postback

			if (canVote && !poll.IsExpired && cntx.IsWebRequest && !Globals.IsNullorEmpty(cntx.Context.Request.Form["PollVoteCommand"]) && !Globals.IsNullorEmpty(cntx.Context.Request.Form["PollVote"]))
			{
				if (!poll.HasVoted(cntx.User.UserID ))
				{
					PollItem item = poll.GetPollItemByAnswerID(cntx.Context.Request.Form["PollVote"]);
					if (item != null)
					{
						Polls.Vote(post.PostID, cntx.User.UserID, item.AnswerID);
						poll.Voters[cntx.User.UserID] = item.AnswerID;
						item.Increment();
						hasVoted = true;
					}
				}
			}

			#endregion

			foreach (PollItem a in poll.Answers)
			{
				totalVotes += a.Total;
			}

            ui.AppendFormat("<div class=\"CommonPollArea\"><h4 class=\"CommonPollQuestion\">{0}</h4><div class=\"CommonPollContent\"><div class=\"CommonPollDescription\">{1}</div>", poll.Question, poll.Description);

			#region Voting Pane

			if (canVote && !hasVoted && !poll.IsExpired)
			{
				ui.Append("<div id=\"PollVoteArea\" class=\"CommonPollSwitchedContent\" style=\"display: block;\"><ul class=\"CommonPollAnswerList\">");

				foreach (PollItem a in poll.Answers)
				{
					ui.AppendFormat("<li><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td><input type=\"radio\" name=\"PollVote\" value=\"{0}\" /></td><td class=\"CommonPollAnswer\">{1}</td></tr></table>", a.AnswerID, a.Answer);
				}
				
				ui.Append("</ul><input name=\"PollVoteCommand\" type=\"submit\" value=\"Vote\" /></div>");
			}

			#endregion

			#region Results Pane
								  
			ui.Append("<div id=\"PollResultsArea\" class=\"CommonPollSwitchedContent\" style=\"display: ");
			if (!canVote || hasVoted || poll.IsExpired)
				ui.Append("block");
			else
				ui.Append("none");
			ui.Append(";\"><ul class=\"CommonPollAnswerList\">");
			
			foreach (PollItem a in poll.Answers)
			{
				if (totalVotes > 0)
					percent = ((double) a.Total) / ((double) totalVotes) * 100;
				else
					percent = 0;

				ui.AppendFormat("<li><div class=\"CommonPollAnswer\">{0} ({1}%)</div><div class=\"CommonPollResultGraph\">", a.Answer, percent.ToString("#0.#"));

				#region Graph

				ui.Append("<img src=\"");
				ui.Append(Globals.GetSkinPath());
				ui.Append("/images/poll_a_start.gif");
				ui.Append("\" height=\"19\" />");

				if (percent > 0)
				{
					ui.Append("<img src=\"");
					ui.Append(Globals.GetSkinPath());
					ui.Append("/images/poll_a_mid.gif");
					ui.Append("\" height=\"19\" width=\"");
					ui.Append(((int) ((percent / 100f) * 250f)).ToString());
					ui.Append("\" />");

					ui.Append("<img src=\"");
					ui.Append(Globals.GetSkinPath());
					ui.Append("/images/poll_a_end.gif");
					ui.Append("\" height=\"19\" />");
				}

				ui.Append("<img src=\"");
				ui.Append(Globals.GetSkinPath());
				ui.Append("/images/poll_none_mid.gif");
				ui.Append("\" height=\"19\" width=\"");
				
				if (percent > 0)
					ui.Append(((int) ((1f - (percent / 100f)) * 250f)).ToString());
				else
					ui.Append("257");

				ui.Append("\" />");

				ui.Append("<img src=\"");
				ui.Append(Globals.GetSkinPath());
				ui.Append("/images/poll_none_end.gif");
				ui.Append("\" height=\"19\" />");

				#endregion

				ui.Append("</div></li>");
			}

			ui.Append("</ul>");
			
			if (hasVoted)
			{
				ui.Append("<div class=\"CommonPollUserVote\">");
				ui.AppendFormat(ResourceManager.GetString("PollModule_UserVote"), poll.GetUserVote(cntx.User.UserID).Answer);
				ui.Append("</div>");
			}

			ui.Append("</div></div>");

			#endregion

			#region Footer

			ui.Append("<div class=\"CommonPollFooter\"><ul class=\"CommonPollFooterList\">");
			if (canVote && !hasVoted && !poll.IsExpired)
			{
				ui.Append("<li><a href=\"#\" onclick=\"TogglePollSwitchedAreas(this); return false;\">");
				ui.Append(ResourceManager.GetString("PollModule_ViewResults"));
				ui.Append("</a></li>");
			}

			ui.Append("<li>");
			ui.AppendFormat(ResourceManager.GetString("PollModule_TotalVotes"), totalVotes);
			ui.Append("</li>");
			
			
			if (poll.PollExpires)
			{
				ui.Append("<li>");

				if (!poll.IsExpired)
					ui.AppendFormat(ResourceManager.GetString("PollModule_PollExpires"), poll.ExpirationDate);
				else
					ui.AppendFormat(ResourceManager.GetString("PollModule_PollExpired"), poll.ExpirationDate);
					
				ui.Append("</li>");
			}

			if (cntx.User.IsAdministrator)
			{
				ui.Append("<li><a href=\"");
				ui.Append(SiteUrls.Instance().PollVoteReport(post.PostID, post.Section.ApplicationType));
				ui.Append("\" target=\"_blank\">");
				ui.Append(ResourceManager.GetString("PollModule_ViewUserVotes"));
				ui.Append("</a></li>");
			}

			ui.Append("</ul></div>");

			#endregion

			ui.Append("</div>");

			#region JavaScript

			if (canVote && !hasVoted && !poll.IsExpired)
			{
				ui.AppendFormat("<script language=\"javascript\">function TogglePollSwitchedAreas(element) {{ var voteArea = document.getElementById('PollVoteArea'); var resultsArea = document.getElementById('PollResultsArea'); if (voteArea && resultsArea) {{	if (voteArea.style.display == 'block') {{ voteArea.style.display = 'none'; resultsArea.style.display = 'block';	element.innerHTML = '{0}'; }} else {{ voteArea.style.display = 'block'; resultsArea.style.display = 'none'; element.innerHTML = '{1}'; }} }} }} </script>", ResourceManager.GetString("PollModule_Vote"), ResourceManager.GetString("PollModule_ViewResults"));
			}

			#endregion

			return ui.ToString();
		}
	}
}

