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

using System;
using System.Collections;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.Controls;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;
using FormLabel = CommunityServer.ControlPanel.Controls.FormLabel;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using Style = CommunityServer.Controls.Style;
using HelpIcon = CommunityServer.ControlPanel.Controls.HelpIcon;

namespace CommunityServer.ControlPanel.PhotoAdmin
{
	/// <summary>
	/// Summary description for SectionEditDetailsControl.
	/// </summary>
	public class SectionEditDetailsControl : BaseGalleryAdminControl
	{
		CSContext csContext = CSContext.Current;

		#region Public Properties

		private int sectionID = -1;
		public int SectionID
		{
			get { return sectionID; }
			set { sectionID = value;}
		}
		private int groupID = -1;
		public int GroupID
		{
			get { return groupID; }
			set { groupID = value;}
		}

		#endregion

		#region Child Controls

		protected YesNoRadioButtonList ynIsActive;
		protected YesNoRadioButtonList ynIsSearchable;
		protected TextBox SectionName;
		protected TextBox AppKey;
		protected TextBox Owners;
		protected Style ControlPanelStyle;
		protected HelpIcon Helpicon6;
		protected FormLabel Formlabel2;
		protected HelpIcon Helpicon4;
		protected FormLabel Formlabel17;
		protected HelpIcon Helpicon5;
		protected FormLabel Formlabel18;
		protected ResourceControl Resourcecontrol38;
		protected HelpIcon Helpicon2;
		protected FormLabel Formlabel1;
		protected RequiredFieldValidator AdminGroupValidator;
		protected HelpIcon HelpIcon1;
		protected FormLabel Formlabel6;
		protected HelpIcon Helpicon3;
		protected FormLabel Formlabel16;
		protected RequiredFieldValidator SectionNameValidator;
		protected RequiredFieldValidator AppKeyValidator;
		protected DropDownList AdminGroupList;
		protected FilterLanguageDropDownList DefaultLanguage;
		protected Literal AppKeyUrlPrefix;
		protected Literal AppKeyUrlSuffix;

		#endregion

		private bool IsNew
		{
			get{return SectionID <= 0;}
		}
		private bool HasGroupID
		{
			get{return GroupID > 0;}
		}
	
		private void Page_Load(object sender, EventArgs e)
		{
			string appKeyUrl = Globals.GetSiteUrls().UrlData.FormatUrl("gallery_ViewGallery", "???");
			if (appKeyUrl.ToLower().EndsWith("/default.aspx"))
				appKeyUrl = appKeyUrl.Substring(0, appKeyUrl.Length - 13);

			int index = appKeyUrl.IndexOf("???");
			if (index > -1)
			{
				AppKeyUrlPrefix.Text = appKeyUrl.Substring(0, index);
				AppKeyUrlSuffix.Text = appKeyUrl.Substring(index + 3);
			}


			if(!Page.IsPostBack)
			{
				BindGroupList();
				BindSettingsData();
			}
		}

		#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 EventHandler(this.Page_Load);

		}


		#endregion

		private void BindGroupList()
		{
			ArrayList groups = GalleryGroups.GetGroups(true, true, true); 
				foreach(Group group in groups)
					AdminGroupList.Items.Add(new ListItem(group.Name, group.GroupID.ToString()));
		}

		#region Section Settings

		private void BindSettingsData()
		{
			Gallery g;
			if(IsNew)
			{
				g = new Gallery();

				if(HasGroupID)
					AdminGroupList.Items.FindByValue(this.GroupID.ToString()).Selected = true;
                else
                {
                    ListItem li = AdminGroupList.Items.FindByValue(GalleryConfiguration.Instance().DefaultGroupID.ToString());
                    if (li != null)
                        li.Selected = true;
                }

			}
			else
			{
				g = CommunityServer.Galleries.Galleries.GetGallery(this.SectionID);
				AdminGroupList.Items.FindByValue(g.GroupID.ToString()).Selected = true;
				this.GroupID = g.GroupID;
			}
			ynIsActive.SelectedValue = g.IsActive;
			ynIsSearchable.SelectedValue = g.IsSearchable;
			AppKey.Text = g.ApplicationKey;
			Owners.Text = g.Owners;
			SectionName.Text = g.Name;
			DefaultLanguage.SelectedValue = g.DefaultLanguage;

		}

		private void Update() 
		{
			Gallery g = CommunityServer.Galleries.Galleries.GetGallery(this.SectionID);

			if(Globals.IsNullorEmpty(AppKey.Text))
				AppKey.Text = SectionName.Text;

			if(g.ApplicationKey != AppKey.Text.ToLower())
			{
               
				// If the ApplicationKey was changed, we need to rename a few things... but only if the user is an admin
				if(GalleryConfiguration.Instance().CreateGalleryDirectories)
				{
					string formattedKey = null;
					Globals.ValidateApplicationKey(AppKey.Text, out formattedKey);
					if(g.ApplicationKey != formattedKey)
					{
	
						if(CheckForDuplicate(formattedKey, this.SectionID))
						{
							AppKeyValidator.IsValid = false;
							//throw new ArgumentException(ResourceManager.GetString("CP_PhotosAdmin_SectionEdit_Settings_AppKey_DuplicateNameException"));
							return;
						}
					
						string oldPath = Globals.GetSiteUrls().Locations["galleries"] + g.ApplicationKey;
						string newPath = Globals.GetSiteUrls().Locations["galleries"] + formattedKey;
						WebDirectory.Move(oldPath, newPath);
						g.ApplicationKey = formattedKey;
					}
				}
			}

			g.IsActive =  ynIsActive.SelectedValue;
			g.Owners = Owners.Text;
			g.IsSearchable =  ynIsSearchable.SelectedValue;
			g.Name = SectionName.Text;
			g.GroupID = int.Parse(AdminGroupList.SelectedValue); 
			g.DefaultLanguage = DefaultLanguage.SelectedValue;

			CommunityServer.Galleries.Galleries.Update(g);

		}

		private void Create()
		{

			//Validate we are an Admin
			if(!csContext.User.IsGalleryAdministrator)
				throw new CSException(CSExceptionType.AdministrationAccessDenied);

			//Validate the application key
			if(Globals.IsNullorEmpty(AppKey.Text))
				AppKey.Text = SectionName.Text;

			string formattedKey = null;
			Globals.ValidateApplicationKey(AppKey.Text, out formattedKey);

			if(CheckForDuplicate(formattedKey, -1))
			{
				AppKeyValidator.IsValid = false;
				//throw new ArgumentException(ResourceManager.GetString("CP_PhotosAdmin_SectionEdit_Settings_AppKey_DuplicateNameException"));
				return;
			}
			Gallery g = new Gallery();
			g.ApplicationKey = formattedKey;
	
			//Set remaining gallery settings
			g.GroupID = int.Parse(AdminGroupList.SelectedValue) ;
			g.Name = SectionName.Text;
			g.IsActive = ynIsActive.SelectedValue;
			g.SettingsID = csContext.SiteSettings.SettingsID;
			g.ApplicationType = ApplicationType.Gallery;
			g.DefaultLanguage = DefaultLanguage.SelectedValue;

			if(!Globals.IsNullorEmpty(Owners.Text))
				g.Owners = Owners.Text;

			g.IsSearchable =  ynIsSearchable.SelectedValue;

			//Create The Gallery
			g.SectionID = CommunityServer.Galleries.Galleries.AddGallery(g);

			//Update the page SectionID for saving the permissions
			this.SectionID = g.SectionID;
			
			//Create the Folder on the webserver
			if(GalleryConfiguration.Instance().CreateGalleryDirectories)
				WebDirectory.Create(Globals.GetSiteUrls().Locations["galleries"] + g.ApplicationKey);
		}
		
		protected bool CheckForDuplicate(string applicationKey, int CurrentSectionID)
		{
			// Check to make sure sure it isn't a duplicate gallery
			foreach(Gallery g in CommunityServer.Galleries.Galleries.GetGalleries(csContext.User.UserID, false, false, false))
				if(string.Compare(g.ApplicationKey, applicationKey, true) == 0 && g.SectionID != CurrentSectionID)
						return true;
			return false;
		}


		#endregion

		public void Save()
		{
			if(!csContext.User.IsGalleryAdministrator)
				throw new CSException(CSExceptionType.AdministrationAccessDenied);
			
			if(IsNew)
				Create();
			else
				Update();
		}




	}
}
