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

using System;
using System.Collections;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Files.Components;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using ResourceLinkButton = CommunityServer.ControlPanel.Controls.ResourceLinkButton;

namespace CommunityServer.ControlPanel.Files
{
	/// <summary>
	/// Summary description for FileEditor.
	/// </summary>
	public class FileEditor : BaseFilesPage
	{
		#region Controls

		protected Controls.ResourceControl ErrorMessage;
		protected ResourceLinkButton PostButton;
		protected Literal PreviewTitle;
		protected Literal PreviewBody;
		protected HtmlGenericControl ErrorPanel;
		protected HtmlGenericControl Post;
		protected HtmlGenericControl Preview;
		protected TextBox PostSubject;
		protected Editor PostBody;
		protected HtmlInputHidden TempAttachmentGuid;
		protected ModalLink UploadFile;
		protected Label FileName;
		protected YesNoRadioButtonList IsApproved;
		protected TagEditor Tags;

		#endregion

		protected Modal Modal1;
		protected Script Script1;
		protected CSContext context = CSContext.Current;

		private void Page_Load(object sender, EventArgs e)
		{
			AjaxManager.Register(this,"FileEditor");
			this.IsInEdit = true;
			PostButton.Attributes.Add("onclick", "if (!validateFile()) { return false; };");
		    PanelPage.RegisterControlForByPass(PostButton);
			UploadFile.Url = FileGalleryUrls.Instance().UploadFile(this.CurrentFolder.SectionID);

			if (context.PostID <= 0)
				Entries.CreateEntryAccessCheck();

			if (!Page.IsPostBack)
			{
				Bind();
			}
			else
			{
				if (context.PostID > 0)
					UploadFile.Text = ResourceManager.GetString("CP_Files_FileEditor_FileOrUrl_UpdateUpload");
				else
					UploadFile.Text = ResourceManager.GetString("CP_Files_FileEditor_FileOrUrl_Upload");

				if (TempAttachmentGuid.Value != "NotNew" && TempAttachmentGuid.Value != "")
					FileName.Text = TempAttachmentGuid.Value.Split(':')[1];
			}

		}

		void Bind()
		{
			if (context.PostID > 0)
			{
				Entry post = Entries.GetEntry(context.PostID, true);
				if (post != null)
				{
					PopulateCategories();

					PostSubject.Text = Server.HtmlDecode(post.Subject);
					PostBody.Text = post.Body;
					
					ArrayList categories = Entries.GetEntryCategories(post, false);
					string[] tags = new string[categories.Count];
					for(int i = 0; i < categories.Count; i++)
						tags[i] = ((PostCategory) categories[i]).Name;

					Tags.SelectedTags = tags;
					
					FileName.Text = post.Attachment.FileName;
					TempAttachmentGuid.Value = "NotNew";
					UploadFile.Text = ResourceManager.GetString("CP_Files_FileEditor_FileOrUrl_UpdateUpload");

					IsApproved.SelectedValue = post.IsApproved;
				}
			}
			else
			{
				IsApproved.SelectedValue = true;
				PopulateCategories();
				UploadFile.Text = ResourceManager.GetString("CP_Files_FileEditor_FileOrUrl_Upload");
			}
		}

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

		#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.PostButton.Click += new EventHandler(this.PostButton_Click);
			this.Load += new EventHandler(this.Page_Load);
		}

		#endregion

		private void PostButton_Click(object sender, EventArgs e)
		{
			if (!Page.IsValid)
				return;

			Entry post = null;

			if (context.PostID > 0)
			{
				post = Entries.GetEntry(context.PostID, false);
			}
			else
			{
				post = new Entry();
				post.Username = context.User.Username;
				post.AuthorID = context.User.UserID;
				post.SectionID = CurrentFolder.SectionID;
				post.ParentID = 0;
				post.PostType = PostContentType.HTML;
				post.PostID = -1;
			}
			
			post.Subject = PostSubject.Text;
			post.Body = PostBody.Text;
			post.PostType = PostContentType.HTML;
			post.IsApproved = IsApproved.SelectedValue;
			post.Categories = Tags.SelectedTags;

			post.UserTime = DateTime.Now;
			post.PostDate = UserTime.ConvertToServerTime(post.UserTime);

			int postID = context.PostID;
			if (postID > 0)
			{
				if (TempAttachmentGuid.Value != String.Empty && TempAttachmentGuid.Value != "NotNew")
					Entries.Update(post, new Guid(TempAttachmentGuid.Value.Split(':')[0]));
				else
					Entries.Update(post);
			}
			else
				Entries.Create(this.CurrentFolder.SectionID, post, new Guid(TempAttachmentGuid.Value.Split(':')[0]));

			Response.Redirect("filelist.aspx");
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string PreviewPost(string text)
		{
			Entry post = new Entry();
			post.Username = context.User.Username;
			post.AuthorID = context.User.UserID;
			post.SectionID = CurrentFolder.SectionID;
			post.ParentID = 0;
			post.PostType = PostContentType.HTML;
			post.Body = text;
			post.Subject = "";

			Entries.FormatPost(post);
			
			return post.FormattedBody;
		}
	}
}
