//------------------------------------------------------------------------------
// <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.Controls;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Galleries;
using CommunityServer.Galleries.Components;
using CommunityServer.Galleries.Controls;
using FormLabel = CommunityServer.ControlPanel.Controls.FormLabel;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using HelpIcon = CommunityServer.ControlPanel.Controls.HelpIcon;

namespace CommunityServer.ControlPanel.Photos
{
	/// <summary>
	/// Summary description for CategoryForm.
	/// </summary>
	public class CategoryForm : BaseGalleryPage
	{

		#region Child Controls

		protected PlaceHolder PreviewContainer, ParentHighlightContainer;

		protected TextBox CategoryName;
		protected Controls.FormLabel Formlabel1;
		protected TextBox CategoryDesc;
		protected Controls.FormLabel Formlabel2;
		protected CheckBox CategoryEnabled;
		protected RequiredFieldValidator RequiredFieldValidator1;
		protected Controls.FormLabel Formlabel3;
		protected FormLabel Formlabel4;
		protected RequiredFieldValidator ParentIDValidator;
		protected IButton SaveButton;
		protected HelpIcon HelpIcon1;
		protected HelpIcon Helpicon2;
		protected HelpIcon Helpicon3;
		protected HelpIcon Helpicon4;
		protected ParentCategoryDropDown CategoryParentID;
		protected MPContent bcr;
		protected MPContainer MPContainer;
		protected HtmlGenericControl PreviewHightlight;
		protected HelpIcon Helpicon5;
		protected FormLabel Formlabel5;
		protected DropDownList HighlightID;
		protected ResourceControl ResourceControl1;

		#endregion

		private int categoryID = -1;
		private int parentID = -1;

		private bool IsNew
		{
			get{return categoryID == -1;}
		}

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

			CSContext cntx = CSContext.Current;
			categoryID = cntx.GetIntFromQueryString("categoryID", categoryID);
			parentID = cntx.GetIntFromQueryString("parentID", parentID);

			if(IsNew)
				Head.AddTitle(Components.ResourceManager.GetString("CP_Photos_CategoryEdit_NewCategory"), this.Context);
			else
				Head.AddTitle(Components.ResourceManager.GetString("CP_Photos_CategoryEdit_EditCategory"), this.Context);
	
			if(!IsPostBack && !this.IsCallBack)
			{
				GalleryPostCategory pc = GetCategory();	        
				CategoryName.Text = Server.HtmlDecode(pc.Name);
				CategoryDesc.Text = pc.Description;
				CategoryEnabled.Checked = pc.IsEnabled;
				CategoryParentID.SectionID = CurrentGallery.SectionID;
				CategoryParentID.DataBind();

				GalleryThreadQuery query = new GalleryThreadQuery();
				query.SectionID = CurrentGallery.SectionID;
				query.CategoryID = categoryID;
				query.ApplicationPostType = GalleryPostType.Image;
				query.PageSize = int.MaxValue;
				query.SortOrder = SortOrder.Descending;
				ThreadSet ts = GalleryPosts.GetPictures(query, false);
			
				foreach(GalleryPost post in ts.Threads)
				{
					if(post.IsPostEnabled)
						HighlightID.Items.Add(new ListItem(post.Subject,post.PostID.ToString()));
				}
				HighlightID.Items.Insert(0,new ListItem(Components.ResourceManager.GetString("CP_Photos_CategoryEdit_DefaultHighlight"),"-1"));

				ConfigurePage(pc);

				PreviewHightlight.InnerHtml = GetHightlightHTML(pc.FeaturedPostID);

				if (CurrentGallery.CategorizationType != CategorizationType.Album)
				{
					ParentHighlightContainer.Visible = false;
					PreviewContainer.Visible = false;
				}
			}
		}

		#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);
			this.SaveButton.Click += new EventHandler(SaveButton_Click);
		}
		
		/// <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 EventHandler(this.Page_Load);

		}
		#endregion

		private void ConfigurePage(GalleryPostCategory category)
		{
			if(category.ParentID == 0 && parentID > 0 )
				CategoryParentID.SelectedCategoryID = parentID;
			else
				CategoryParentID.SelectedCategoryID = category.ParentID;

			ListItem li = HighlightID.Items.FindByValue(category.FeaturedPostID.ToString());
			if(li != null)
				li.Selected = true;
		}

		protected GalleryPostCategory GetCategory()
		{
			GalleryPostCategory pc = null;

			if(IsNew)
			{
				pc = new GalleryPostCategory();
				pc.SectionID = CurrentGallery.SectionID;
			}
			else
			{
				pc = GalleryPostCategory.Parse(PostCategories.GetCategory(categoryID,CurrentGallery.SectionID,true, true)) ;
				if(pc == null)
					throw new Exception("Album could not be found");
			}

			return pc;
		}

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

			PostCategory pc = GetCategory();
			//Check to see that the category isnt a duplicate
			if(pc.CategoryID < 0)
			{
				ArrayList al = PostCategories.GetCategories(CurrentGallery.SectionID, true, true, -1, true);
				foreach(PostCategory c in al)
					if(c.Name.ToLower()  == CategoryName.Text.ToLower() )
					{
						RequiredFieldValidator1.Text = string.Concat("<br />",ResourceManager.GetString("CP_Photos_CategoryEdit_Duplicate")) ;
						RequiredFieldValidator1.IsValid = false;
						return;
					}
			}
			pc.Name = CategoryName.Text;
			pc.Description = CategoryDesc.Text;
			pc.IsEnabled = CategoryEnabled.Checked;

			// Make sure the parent isn't the same as the current ID
			if(CategoryParentID.SelectedCategoryID != 0)
			{
				PostCategory pcat = PostCategories.GetCategory(CategoryParentID.SelectedCategoryID, CategoryParentID.SectionID, true, true);
				if((pcat.CategoryID == pc.CategoryID) || (pcat.Path.IndexOf("/" + pc.CategoryID + "/") != -1))
					((RequiredFieldValidator)FindControl( "ParentIDValidator" )).IsValid = false;
			}

			pc.ParentID = CategoryParentID.SelectedCategoryID;

			// Update the database is the page is valid
			if(!Page.IsValid)
				return;

			pc.FeaturedPostID = Globals.SafeInt(HighlightID.SelectedValue, -1) ;

			if(pc.CategoryID > 0)
				PostCategories.UpdateCategory(pc);
			else
				PostCategories.CreateCategory(pc);

			Modal.ClosePage(Page) ;

		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string GetHightlightPreview(string featuredPostID)
		{
				int postID = Globals.SafeInt(featuredPostID, -1) ;
				return GetHightlightHTML(postID);
		}
			
		private string GetHightlightHTML(int featuredPostID)
		{
			string imageTag = "<img src=\"{0}\" alt=\"{1}\" />";


			if(featuredPostID > 0)
				return  string.Format(imageTag, GalleryUrls.Instance().ThumbnailURL(CurrentGallery.ApplicationKey, featuredPostID), "Category Highlight Image");
			else
				return string.Format(imageTag, GalleryUrls.Instance().DefaultHighlightImage, "Default Category Highlight Image") ;

		}
			
	}
}

