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

using System;
using System.Collections;
using System.IO;
using System.Security;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Components;
using CommunityServer.ControlPanel.Controls;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using FormLabel = CommunityServer.ControlPanel.Controls.FormLabel;
using ResourceControl = CommunityServer.ControlPanel.Controls.ResourceControl;
using HelpIcon = CommunityServer.ControlPanel.Controls.HelpIcon;

namespace CommunityServer.ControlPanel.BlogAdmin
{
	/// <summary>
	/// Summary description for SectionEditDetailsControl.
	/// </summary>
	public class SectionEditDetailsControl : BaseBlogAdminControl
	{

		#region Child Controls

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

		protected ControlPanel.Controls.StatusMessage Status;

		CSContext csContext = CSContext.Current;

		#endregion

		#region 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;}
		}

		private bool IsNew
		{
			get{return sectionID <= 0;}
		}
		private bool HasGroupID
		{
			get{return GroupID > 0;}
		}

		#endregion

		override protected void OnInit(EventArgs e)
		{
			this.Load += new EventHandler(this.Page_Load);
			base.OnInit(e);
		}
		
		private void Page_Load(object sender, EventArgs e)
		{
			sectionID = csContext.GetIntFromQueryString("SectionID", -1);

			string appKeyUrl = Globals.GetSiteUrls().UrlData.FormatUrl("weblogapplication", "???");
			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();
			}
		}
		
		private void BindGroupList()
		{
			ArrayList groups = WeblogGroups.GetWeblogGroups(true, true, true); 
			foreach(Group group in groups)
				AdminGroupList.Items.Add(new ListItem(group.Name, group.GroupID.ToString()));

            
		}


		public void Save()
		{
			//Validate we are an Admin
			if(!CSContext.Current.User.IsBlogAdministrator)
				throw new CSException(CSExceptionType.AdministrationAccessDenied);

			if(IsNew)
				Create();
			else
				Update();

		}


		#region Weblog Settings

		private void BindSettingsData()
		{
			Weblog w;

			if(IsNew)
			{
				w = new Weblog();

				if(HasGroupID)
					AdminGroupList.Items.FindByValue(this.GroupID.ToString()).Selected = true;
				else
				{
					ListItem li = AdminGroupList.Items.FindByValue(WeblogConfiguration.Instance().DefaultGroupID.ToString());
					if(li != null)
						li.Selected = true;
				}
			}
			else
			{
				w = Weblogs.GetWeblog(this.sectionID, true, false);
				AdminGroupList.Items.FindByValue(w.GroupID.ToString()).Selected = true;
			}

			ynIsActive.SelectedValue = w.IsActive;
			ynEnableAggBugs.SelectedValue = w.EnableAggBugs;
			ynIsSearchable.SelectedValue = w.IsSearchable;
			ynIsCommunityAggregated.SelectedValue = w.IsCommunityAggregated;
			AppKey.Text = w.ApplicationKey;
			SectionName.Text = w.Name;
			Owners.Text = w.Owners;
			DefaultLanguage.SelectedValue = w.DefaultLanguage;
		}


		private void Update() 
		{
			Weblog w = Weblogs.GetWeblog(this.sectionID, true, false);

			if(w.ApplicationKey != AppKey.Text.ToLower())
			{
				string formattedKey = null;
				Globals.ValidateApplicationKey(AppKey.Text, out formattedKey);
                
				if(w.ApplicationKey != formattedKey)
				{
					if(Weblogs.Exists(formattedKey, this.SectionID))
					{
						AppKeyValidator.IsValid = false;
						return;
					}
					string oldPath = Globals.GetSiteUrls().Locations["weblogs"] + w.ApplicationKey;
					string newPath = Globals.GetSiteUrls().Locations["weblogs"] + formattedKey;

					if(WeblogConfiguration.Instance().CreateBlogDirectories)
						WebDirectory.Move(oldPath,newPath);

					w.ApplicationKey = formattedKey;
				}
			}

			w.GroupID = int.Parse(AdminGroupList.SelectedValue);
			w.IsActive =  ynIsActive.SelectedValue;
			w.Owners = Owners.Text;
			w.Name = SectionName.Text;
			w.IsSearchable =  ynIsSearchable.SelectedValue;
			w.EnableAggBugs = ynEnableAggBugs.SelectedValue;
			w.IsCommunityAggregated = ynIsCommunityAggregated.SelectedValue;
			w.DefaultLanguage = DefaultLanguage.SelectedValue;
			Weblogs.Update(w);

		}


		private void Create()
		{

			//Validate we are an Admin
			if(!csContext.User.IsBlogAdministrator)
				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(Globals.IsNullorEmpty(formattedKey) || Weblogs.Exists(formattedKey, -1))
			{
				AppKeyValidator.IsValid = false;
				return;
			}
			Weblog w = new Weblog();
			w.ApplicationKey = formattedKey;
	
			//Set remaining section settings
			w.GroupID = int.Parse(AdminGroupList.SelectedValue) ;
			w.Name = SectionName.Text;
			w.IsActive = ynIsActive.SelectedValue;
			w.SettingsID = csContext.SiteSettings.SettingsID;
			w.ApplicationType = ApplicationType.Weblog;

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

			w.IsSearchable =  ynIsSearchable.SelectedValue;
			w.EnableAggBugs = ynEnableAggBugs.SelectedValue;
			w.IsCommunityAggregated = ynIsCommunityAggregated.SelectedValue;
			w.DefaultLanguage = DefaultLanguage.SelectedValue;

			//Create The Blog
			w.SectionID = Weblogs.Add(w);

			//Update the page SectionID for saving the permissions
			this.SectionID = w.SectionID;
			
			if(WeblogConfiguration.Instance().CreateBlogDirectories)
				Weblogs.CreateBlogDirectory(w);

		}


		//		protected bool CheckForDuplicate(string applicationKey, int CurrentSectionID)
		//		{
		//			// Check to make sure sure it isn't a duplicate blog
		//			foreach(Weblog w in Weblogs.GetWeblogs(false, true, true))
		//				if(string.Compare(w.ApplicationKey, applicationKey, true) == 0 && w.SectionID != CurrentSectionID)
		//					return true;
		//			return false;
		//		}

		#endregion

	}
}
