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

using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Controls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Galleries;
using CommunityServer.Galleries.Components;
using CommunityServer.Galleries.Controls;
using System.Collections;
using Calendar = ComponentArt.Web.UI.Calendar;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using Script = CommunityServer.Controls.Script;

namespace CommunityServer.ControlPanel.Photos
{
	/// <summary>
	///		Summary description for Skin_CreateEditBlogPost.
	/// </summary>
	public class PostEditControl : BaseGalleryControl
	{
		protected Literal PreviewTitle;
		protected Literal PreviewBody;
		protected HtmlGenericControl Preview;
		protected Editor PostBody;
		protected TextBox postName;
		protected TextBox postExcerpt;
		protected CommentModerationDropDownList ModerationDDL;
		protected GalleryImage Galleryimage1;
		protected System.Web.UI.WebControls.CustomValidator pictureDataValidator; //PictureData
		protected RequiredFieldValidator postSubjectValidator;
		protected RegularExpressionValidator vRegexPostName;
		protected CategoryChecklistControl CategoryChecklist1;
		protected Calendar DatePicker;
		protected DropDownRange HourPicker;
		protected DropDownRange MinutePicker;
		protected DropDownList AMPM;
		protected Modal Modal1;
		protected Modal Modal2;
		protected int PostID;
		protected FeedbackNotificationDropDownList NotificationType;
		protected Script Script1;
		protected Panel ExistingAttachmentPanel;
		protected Panel ServerUploadPanel;
		protected Literal ExistingFileName;
		protected HtmlInputHidden ServeruploadtempID;
		protected TextBox ServerFriendlyFileName;
		protected TextBox ServerFileName;
		protected Script Script2;
		protected CommunityServer.ControlPanel.Controls.StatusMessage Status;
		protected PlaceHolder AlbumSelectionContainer, TagSelectionContainer;
		protected TagEditor Tags;

		protected CSContext context = null;

	
		private void Page_Load(object sender, EventArgs e)
		{
			AjaxManager.Register(this,"PostEditControl");

			context = CSContext.Current;
			PostID = context.PostID;

			this.PanelPage.IsInEdit = true;

			pictureDataValidator.Enabled = (context.PostID <= 0); //Picture is required

			if (!Page.IsPostBack && !this.GalleryPage.IsCallBack)
			{
				Bind();
			}

			ValidatePictureDataClient();
			//Page.RegisterStartupScript("DisableFileNameBox","<SCRIPT type='text/javascript'>document.getElementById('" + this.ServerFileName.ClientID  + "').disabled=true;</script>") ;

		}

//		private void RegisterAddAttachmentPopup()
//		{
//			string script = @"<script type=""text/javascript"">initPopUp();{0};</script>";
//			Page.RegisterStartupScript("AttachmentPopup",String.Format(script, ModalHelper.BuildHandler(Modal2).TrimEnd(';'))) ; 
//		}


		private void Bind()
		{
			GalleryPost post = null;

			vRegexPostName.ValidationExpression = GalleryPosts.PostNamePattern;
			vRegexPostName.Text = ResourceManager.GetString("CP_Photos_PostEdit_Name_RegexValidator");

			if (context.PostID > 0)
			{
				post = GalleryPosts.GetPicture(context.PostID, true);
				if (post != null)
				{

					PostBody.Text = post.Body;
					postExcerpt.Text = post.Excerpt;
					postName.Text = post.Name;
					ModerationDDL.Items.FindByValue(post.ModerationType.ToString()).Selected = true;
					SetDate(post.PostDate);
					NotificationType.SelectedValue = post.FeedbackNotificationType;

					// Update the thumbnail
					Galleryimage1.GalleryPost = post;
					Galleryimage1.PostID = post.PostID;
					Galleryimage1.NavigateUrl = GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey, post );
					Galleryimage1.DataBind();

					if(Globals.IsNullorEmpty(post.AttachmentFilename))
					{
						ExistingAttachmentPanel.Visible = false;
					}
					else
					{
						PostAttachmentMetaData attachment = post.Attachment;
						if(attachment != null)
						{
							ExistingAttachmentPanel.Visible = true;
							ExistingFileName.Text = attachment.FileName;
							
							//Galleryies uses the ServerFriendlyFileName as the post subject
							ServerFriendlyFileName.Text = post.Subject;
						}
                        
					}

					bool hasMultipleOwners = post.Gallery.OwnerArray.Length > 1;
					SetYesNo(post.PostConfig, post.IsApproved, !post.IsLocked, post.EnableAllOwnerNotification, post.EnableRatings, post.EnableTrackBacks, hasMultipleOwners);

					if (CurrentGallery.CategorizationType == CategorizationType.Album)
					{
						CategoryChecklist1.SelectedNodes = GalleryPosts.GetPictureCategories(post);
						TagSelectionContainer.Visible = false;
					}
					else
					{
						PopulateCategories();
						Tags.SelectedTags = GetTagNamesFromCategories(GalleryPosts.GetPictureCategories(post));
						AlbumSelectionContainer.Visible = false;
					}
				}
			}
			else
			{
				//RegisterAddAttachmentPopup();

				ExistingAttachmentPanel.Visible = false;
				SetDate(UserTime.CurrentUserTime);
				ModerationDDL.Items.FindByValue(CurrentGallery.ModerationTypeDefault.ToString()).Selected = true;
                
				SetYesNo(CurrentGallery.DefaultPostConfig, true, true, false, this.CurrentGallery.EnableRatingsDefault, CurrentGallery.EnableTrackbacksDefault, false);
				int categoryID = context.GetIntFromQueryString("cid",context.GetIntFromQueryString("categoryid", -1));
				CategoryChecklist1.SetSingleSelectedNode(categoryID, this.GalleryPage.CurrentGallery.SectionID); 

				if (CurrentGallery.CategorizationType == CategorizationType.Album)
				{
					TagSelectionContainer.Visible = false;
				}
				else
				{
					AlbumSelectionContainer.Visible = false;
					PopulateCategories();
				}
			}
		}

		private string[] GetTagNamesFromCategories(ArrayList categories)
		{
			string[] tags = new string[categories.Count];
			int i = 0;
			foreach (PostCategory pc in categories)
			{
				tags[i] = pc.Name;
				i++;
			}		
	
			return tags;
		}

		private void PopulateCategories()
		{
			Tags.AvailableTags = PostCategories.GetCategories(this.CurrentGallery.SectionID, true, true);
		}

		private bool GetYesNo(string ynID)
		{
			return (FindControl(ynID) as YesNoRadioButtonList).SelectedValue;
		}

		private void PopulateFromYesNo(GalleryPost post)
		{
			bool isPost = this.PostType == GalleryPostType.Image;
			post.IsLocked = !GetYesNo("ynEnableReplies");
			post.IsApproved = GetYesNo("ynPublished");
			post.EnableRatings = GetYesNo("ynEnableRatings");
			post.EnableTrackBacks = GetYesNo("ynEnableTrackBacks");
			post.EnableOrderPrints = GetYesNo("ynEnableOrderPrints");
			post.EnableAllOwnerNotification = GetYesNo("ynNotifyAllOwners");
			if (isPost)
			{
				//these features are not implimented in the gallery
				//post.IsAggregated = GetYesNo("ynAggregatePost");
				//post.IsCommunityAggregated = GetYesNo("ynCommunity");
				//post.SyndicateExcerpt = GetYesNo("ynSyndicateExcerpt");
			}

		}

		private void EnableYesNo(string ynID, bool Selected, bool enable)
		{
			YesNoRadioButtonList yn = FindControl(ynID) as YesNoRadioButtonList;
			if (yn != null)
			{
				yn.SelectedValue = Selected;

				if (!enable)
					FindControl(ynID + "_row").Visible = false;
			}
		}

		
		private void SetYesNo(GalleryPostConfig gc, bool isPublished, bool allowReplies, bool notifyAllOwners, bool rate, bool track, bool hasMultipleOwners)
			{
			bool isPost = this.PostType == GalleryPostType.Image;
			EnableYesNo("ynEnableReplies", allowReplies, true);
			EnableYesNo("ynPublished", isPublished, true);
			EnableYesNo("ynAggregatePost", PostConfigHelper.IsPostConfigSelected(gc, GalleryPostConfig.IsAggregated), isPost);
			EnableYesNo("ynCommunity", PostConfigHelper.IsPostConfigSelected(gc, GalleryPostConfig.IsCommunityAggregated), isPost);
			EnableYesNo("ynSyndicateExcerpt", PostConfigHelper.IsPostConfigSelected(gc, GalleryPostConfig.SyndicateExcerpt), isPost);
			EnableYesNo("ynEnableOrderPrints", CurrentGallery.EnableOrderPrints, CurrentGallery.EnableOrderPrintsOverride);
			EnableYesNo("ynEnableRatings", rate, true);
			EnableYesNo("ynEnableTrackBacks", track, true);
			EnableYesNo("ynNotifyAllOwners", notifyAllOwners, hasMultipleOwners);

		}

		
		#region Web Form Designer generated code

		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);


		}

		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
		}

		#endregion

		
		public int Save()
		{
			if (!Page.IsValid)
				return -2;

			GalleryPost post = null;

			if (context.PostID > 0)
				post = GalleryPosts.GetPicture(context.PostID);
			else
			{
				post = new GalleryPost();
				post.Username = context.User.Username;
				post.SectionID = CurrentGallery.SectionID;
				post.ParentID = 0;
				post.GalleryPostType = this.PostType;
				post.PostID = -1;

			}

			if(postName.Text.Length > 0)
			{
				GalleryThreadQuery query = new GalleryThreadQuery();

				query.PostName = postName.Text;
				query.RequireSectionIsActive = false;

				ThreadSet ts = GalleryPosts.GetPictures(query, false);

				if(ts.TotalRecords > 0)
				{
					int PostIDfromName = ((Post)ts.Threads[0]).PostID ;
					if (PostIDfromName!= post.PostID)
					{
						Status.Success = false;
						Status.ResourceName = "Weblog_Exception_DuplicatePostName";
						Status.Visible = true;
						return -2;
					}
				}
			}

			post.Name = postName.Text;
			post.Subject = ServerFriendlyFileName.Text;
			post.Excerpt = postExcerpt.Text;	
			post.Body = PostBody.Text;
			post.PostType = PostContentType.HTML;
			post.FormattedBody = null;

			PopulateFromYesNo(post);

			if (CurrentGallery.CategorizationType == CategorizationType.Album)
			{
				post.Categories = CategoryChecklist1.SelectedNodeNames();
			}
			else
			{
				post.Categories = Tags.SelectedTags;
			}

			post.ModerationType = (CommentModerationType) Enum.Parse(typeof (CommentModerationType), ModerationDDL.SelectedValue, false);

			post.UserTime = GetDate();
			post.PostDate = UserTime.ConvertToServerTime(GetDate());
			post.FeedbackNotificationType = NotificationType.SelectedValue;

			//TODO: Seperate post attachment handeling so we dont use the createpost function to update attacments
			
			PostAttachment pa = null;
			if(!Globals.IsNullorEmpty(ServeruploadtempID.Value))
			{
				GalleryAttachmentSettings fs = GalleryConfiguration.Instance().AttachmentSettings;
				Guid g = new Guid(ServeruploadtempID.Value);
				pa = PostAttachments.ToggleTemporary(g,this.ServerFriendlyFileName.Text, !fs.EnableDataStoreStorage, post.PostID,this.CurrentGallery.SectionID,context.User.UserID,0,0,true);

			}

			if(pa != null)
			{
				int diskQuota = CurrentGallery.GetActiveQuota(GalleryQuotaType.Disk);
				int imageQuota = CurrentGallery.GetActiveQuota(GalleryQuotaType.Image);
				
				bool withinDiskQuota = false;
				try{withinDiskQuota = pa.Length + CurrentGallery.DiskUsage <= diskQuota || diskQuota == -1;}
				catch{}
				
				bool withinImageQuota = imageQuota - CurrentGallery.PostCount > 0 || imageQuota == -1;

				if(withinDiskQuota && withinImageQuota)
				{
				GalleryPosts.CreatePicture(CurrentGallery.SectionID, post, pa);

				//make the thumbnail
				ImageHandling.ScalePicture(post, CurrentGallery.GetThumbnailSettings());
				}
				else
				{
					Status.Success = false;
					if(!withinDiskQuota)
					{
						Status.ResourceName = "CP_Photos_PostEdit_DiskQuota_Exceeded";
					}
					else
					{
						Status.ResourceName = "CP_Photos_PostEdit_ImageQuota_Exceeded";
					}
					Status.Visible = true;
					return -2;
				}
			}
			else
			{
				GalleryPosts.UpdatePicture(post);
			}

			//Find a relevant category to send the user to (instead of sending them to the whole picture list)
			int cid = context.GetIntFromQueryString("cid", -1); //First try the querystring for a hint
			if(cid == -1)
				cid = CategoryChecklist1.GetFirstSelectedNodeID();

			// expire the category cache if text-based categories were added
			PostCategories.ExpireCategoryCache(post.SectionID);

			return cid;

		}

		private void SetDate(DateTime dt)
		{
			DatePicker.SelectedDate = dt;
			int h = dt.Hour;
            if(h == 0)
            {
                h=12;
                AMPM.SelectedIndex = 0;
            }
			else if (h == 12)
			{
				AMPM.SelectedIndex = 1;
			}
			else if(h > 12)
            {
                h = h-12;
                AMPM.SelectedIndex = 1;
            }
			HourPicker.SetSelected(h);
			MinutePicker.SetSelected(dt.Minute);
			//AMPM.Items.FindByValue(dt.ToString("tt")).Selected = true;
		}

		private DateTime GetDate()
		{
			int minute = MinutePicker.GetSelected;
			int hour = HourPicker.GetSelected;
			if(AMPM.SelectedValue == "AM")
			{
				if(hour == 12)
					hour = 0;
			}
			else
			{
				if(hour != 12)
					hour += 12;
			}

			return new DateTime(DatePicker.SelectedDate.Year,DatePicker.SelectedDate.Month,DatePicker.SelectedDate.Day,hour,minute,0);
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string PreviewPost(string text)
		{
			GalleryPost post = new GalleryPost();

			post.Body = text;
			post.Subject = null;

			GalleryPosts.PreviewFormat(post);

			return post.FormattedBody;
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string PreviewAttachment(string AttachmentID)
		{
			string imageURL = "noimg.gif";
			string imageName = "No Image";
			int imageHeight = 200;
			int imageWidth = 300;

			string imageTag = string.Format("<img src=\"{0}\" width={1} height={2} alt=\"{3}\" />",imageURL,imageWidth, imageHeight, imageName);
			GalleryPost post;

			if(IsInteger(AttachmentID))
			{
				post = GalleryPosts.GetPicture(int.Parse(AttachmentID) ); 
				imageURL =  GalleryUrls.Instance().SecondaryThumbnailURL(post);
				imageName = post.Subject;



			}
			else
			{
				Guid guid = new Guid(AttachmentID);
				imageURL =  GalleryUrls.Instance().ViewTempAttachment(CurrentGallery.ApplicationKey, guid) ;
				imageName = "";
			}

				imageTag = string.Format("<img src=\"{0}\" alt=\"{1}\" />",imageURL, imageName);

			return imageTag;
		}

		private bool IsInteger(string i)
		{
			try
			{
				int.Parse(i);
				return true;
			}
			catch
			{
				return false;
			}
		}

		protected void ValidatePictureData(Object sender,  ServerValidateEventArgs args)
		{
			args.IsValid = ServeruploadtempID.Value.ToString().Length > 0;
		}

		private void ValidatePictureDataClient()
		{
			string script = @"<script language=""JavaScript"">
				<!--
				function CheckFileUploadID(sender, args)
				{
					var objTempID = document.getElementById('" + this.ServeruploadtempID.ClientID  + @"');
					var len = 0;
					if (objTempID != null) 
					{
						len = objTempID.value.length;
					}
	
					args.IsValid = len > 0;

				}
				// -->
				</script>";

			Page.RegisterClientScriptBlock("ValidatePictureDataClient", script) ;

		}

	}
}


