//------------------------------------------------------------------------------
// <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.ControlPanel.UI;
using Style = CommunityServer.Controls.Style;

namespace CommunityServer.ControlPanel.Photos
{

	/// <summary>
	/// Summary description for GalleryCommandPage.
	/// </summary>
	public class GalleryCommandPage : BaseGalleryPage
	{

		private static readonly Hashtable commands = new Hashtable();
		private static readonly string CommandKey = "Command";

		protected Literal CommandMessage;
		protected Literal Title;
		protected Button OK_Button;
		protected Style ControlPanelStyle;
		protected HtmlInputButton Cancel_Button;
	
		private void Page_Load(object sender, EventArgs e)
		{
			
			GalleryCommand command = Command();
			OK_Button.Text = command.OK;
			Cancel_Button.Value = command.Cancel;
			Title.Text = command.Title;
			CommandMessage.Text = command.Message(this);
		}

		
		protected GalleryCommand Command()
		{
			GalleryCommand command = commands[CommandKey] as GalleryCommand;
			if(command == null)
			{
				Type t = Type.GetType(Request.QueryString[CommandKey]);
				if(t == null)
					throw new Exception("Type " + Request.QueryString[CommandKey] + " does not exist");

				command = Activator.CreateInstance(t) as GalleryCommand;
				if(command == null)
					throw new Exception("Type " + t.Name + " is not an instance of GalleryCommand");

				commands[Request.QueryString[CommandKey]] = command;
			}

			return command;
		}

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

		}
		#endregion

		private void OK_Button_Click(object sender, EventArgs e)
		{
			GalleryCommand command = Command();
			command.Action(this);
			RegisterCloseScript(command.CloseScript(this));

		}

		private const string closeScript =  "<script language=\"javascript\">function CloseCommandPage() {{ {0} }}</script>";
		private void RegisterCloseScript(string script)
		{
			this.RegisterClientScriptBlock("CloseScript", string.Format(closeScript, script));
			HtmlGenericControl gen = FindControl("body") as HtmlGenericControl;
			gen.Attributes.Add("onload","CloseCommandPage()");
		}
	}

}
