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

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

namespace CommunityServer.ControlPanel.Forums
{
	/// <summary>
	/// Summary description for ManageRanks.
	/// </summary>
	public class CreateUpdateRank : BaseForumPage
	{

		#region Members

		protected TextBox RankName;
		protected TextBox RankMinPost;
		protected TextBox RankMaxPost;
		protected RequiredFieldValidator RankNameValidator;
		protected RequiredFieldValidator RankMinPostValidator;
		protected RequiredFieldValidator RankMaxPostValidator;
		protected ResourceLinkButton SaveButton;
		protected ResourceLinkButton DeleteButton;
		protected HtmlInputFile RankImageUpload;
		protected ResourceLinkButton DeleteImageButton;
		protected Image RankImage;

		int rankID = -1;

		private bool _isEdit = false;
		protected virtual Boolean IsEdit 
		{
			get 
			{
				return _isEdit;
			}
			set 
			{
				_isEdit = value;
			}
		}

		#endregion


		override protected void OnInit(EventArgs e)
		{

			this.Load += new EventHandler(this.Page_Load);
			this.SaveButton.Click += new EventHandler(this.SaveButton_Click);
			this.DeleteButton.Click += new EventHandler(this.DeleteButton_Click);
			this.DeleteImageButton.Click +=new EventHandler(DeleteImageButton_Click);
			DeleteButton.Attributes["onclick"] = string.Format("return confirm('{0}');", Components.ResourceManager.GetString("CP_Forums_CreateUpdateRank_DeleteConfirmation").Replace("'", @"\'") );

			base.OnInit(e);
		}


		private void Page_Load(object sender, EventArgs e)
		{
			CSContext cntx = CSContext.Current;
			rankID = cntx.GetIntFromQueryString("RankID", -1);

			if (rankID > 0)
				this._isEdit = true;

			if ( !Page.IsPostBack ) 
			{
				Bind();

				if (this._isEdit && cntx.GetIntFromQueryString("delete", -1) == 1)
					this.RegisterStartupScript("delete_click", String.Format("<script language=\"javascript\">{0}.click();</script>", this.DeleteButton.ClientID));
			
			}
		}

	
		protected void Bind()
		{
			RankImage.Visible = false;
			DeleteImageButton.Visible = false;

			if (this._isEdit)
			{
				Rank rankToEdit = Ranks.GetRank(rankID);

				if ( rankToEdit != null ) 
				{
					RankName.Text = rankToEdit.RankName;
					RankMinPost.Text = rankToEdit.PostingCountMinimum.ToString();
					RankMaxPost.Text = rankToEdit.PostingCountMaximum.ToString();
					DeleteButton.Visible = true;
					Head.AddTitle(string.Format(Components.ResourceManager.GetString("CP_Forums_CreateUpdateRank_Title_Edit"), rankToEdit.RankName), Context);

					if (!Globals.IsNullorEmpty(rankToEdit.RankIconUrl))
					{
						RankImage.Visible = true;
						DeleteImageButton.Visible = true;
						RankImage.ImageUrl = rankToEdit.RankIconUrl;
						RankImage.AlternateText = rankToEdit.RankName;
					}
				}

			}
			else
			{
				Head.AddTitle(ResourceManager.GetString("CP_Forums_CreateUpdateRank_Title_Add"), Context);
				DeleteButton.Visible = false;
			}


		}


		#region Command Implementations

		protected void DeleteRank() 
		{
			Rank currentRank = Ranks.GetRank(rankID);
			DeleteImage(currentRank);
			Ranks.DeleteRank( currentRank );
		}

		protected bool UpdateRank(Rank currentRank) 
		{

			RankNameValidator.Enabled = true;
			RankMinPostValidator.Enabled = true;
			RankMaxPostValidator.Enabled = true;

			if ( RankName == null || RankMinPost == null || RankMaxPost == null ) 
			{
				return false;
			}

			Page.Validate();

			// Check that the fields were populated
			if(RankName.Text.Trim() == string.Empty)
				RankNameValidator.IsValid = false;
			if(RankMinPost.Text.Trim() == string.Empty)
				RankMinPostValidator.IsValid = false;
			if(RankMaxPost.Text.Trim() == string.Empty)
				RankMaxPostValidator.IsValid = false;

			// Update settings
			currentRank.RankName = RankName.Text.Trim();


			// Check for a rank with a duplicate name
			ArrayList ranks = Ranks.GetRanks();
			foreach(Rank rank in ranks)
			{
				if( (rank.RankName == currentRank.RankName) && (rank.RankId != currentRank.RankId) )
				{
					RankNameValidator.IsValid = false;
					break;
				}
			}

			// Make sure the counts are integers
			try { currentRank.PostingCountMinimum = Int32.Parse( RankMinPost.Text ); }
			catch { RankMinPostValidator.IsValid = false; }
			try { currentRank.PostingCountMaximum = Int32.Parse( RankMaxPost.Text ); }
			catch { RankMaxPostValidator.IsValid = false; }

			// Make sure max is greater than min
			if(currentRank.PostingCountMinimum >= currentRank.PostingCountMaximum)
				RankMaxPostValidator.IsValid = false;

			return true;
		}


		private void UpdateImage (Rank rank, HttpPostedFile postedFile) 
		{
			// validate stream
			if (postedFile.ContentLength <= 0)
			{
				if (rank.RankIconUrl == null)
					rank.RankIconUrl = "";
				return;
			}

			// Remove any existing images, as this one may have a different extension
			DeleteImage(rank);

			// Get extension if one exists
			
			string imageURL = String.Format("{0}/utility/rankicons/{1}", Globals.ApplicationPath, Path.GetFileName(postedFile.FileName));
			string imagePath = CSContext.Current.MapPath( imageURL );
			postedFile.SaveAs(imagePath);

			// Update URL in Rank object
			rank.RankIconUrl = imageURL;

		}


		private void DeleteImage(Rank rank)
		{
			// Delete the image
			string vpath = CSContext.Current.MapPath(rank.RankIconUrl);
			if( File.Exists(vpath) )
				File.Delete(vpath);

			// Update URL in Rank object
			rank.RankIconUrl = String.Empty;
		}


		#endregion

		#region Command Handlers

		private void SaveButton_Click(object sender, EventArgs e) 
		{
			
			Rank currentRank;
			if (this._isEdit)
				currentRank = Ranks.GetRank(rankID);
			else
				currentRank = new Rank();

			if ( UpdateRank(currentRank) )
			{
				// Update only if it is valid
				if(Page.IsValid)
				{
					// Upload image if necessary
					UpdateImage(currentRank, RankImageUpload.PostedFile);

					Ranks.UpdateRank( currentRank );

					this.RegisterStartupScript("reloadgrid", "<script language=\"javascript\"> window.top.document.forms[0].submit();</script>");
					Modal.ClosePage(this);
				}

			}
			
		}

		private void DeleteButton_Click(object sender, EventArgs e) 
		{
			DeleteRank();
			this.RegisterStartupScript("reloadgrid", "<script language=\"javascript\"> window.top.document.forms[0].submit();</script>");
			Modal.ClosePage(this);
		}


		public void DeleteImageButton_Click(Object sender, EventArgs e) 
		{
			
			try 
			{
				Rank currentRank = Ranks.GetRank(rankID);

				// Update only if it is valid
				if(Page.IsValid)
				{
					DeleteImage(currentRank);
					Ranks.UpdateRank( currentRank );
					Bind();
				}

			} 
			catch 
			{
				throw new CSException(CSExceptionType.UnknownError);
			}

		}

		#endregion


	}
}
