using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using Orciid.Core;

namespace Orciid
{
	public class collections : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Panel CreatePanel;
		protected System.Web.UI.WebControls.TextBox TitleTextBox;
		protected System.Web.UI.WebControls.TextBox DescriptionTextBox;
		protected System.Web.UI.WebControls.Button CreateButton;
		protected System.Web.UI.WebControls.TextBox ResourcePathTextBox;
		protected System.Web.UI.WebControls.DropDownList TypeDropDownList;
		protected System.Web.UI.WebControls.Panel CollectionGroupPanel;
		protected System.Web.UI.WebControls.ListBox CollectionGroupListBox;
		protected System.Web.UI.WebControls.Button RemoveCollectionGroupButton;
		protected System.Web.UI.WebControls.TextBox AddNewCollectionGroupTextBox;
		protected System.Web.UI.WebControls.TextBox RenameCollectionGroupTextBox;
		protected System.Web.UI.WebControls.Button AddNewCollectionGroupButton;
		protected System.Web.UI.WebControls.Button RenameCollectionGroupButton;
		protected System.Web.UI.WebControls.LinkButton AddNIXCollectionLinkButton;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ManageCollectionHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CreateNewCollectionHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl TypeSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl TitleSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl DescriptionSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ResourcePathSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AddSpecialCollectionsHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl CollectionGroupsHeading;
		protected System.Web.UI.HtmlControls.HtmlGenericControl AddNewSpan;
		protected System.Web.UI.HtmlControls.HtmlGenericControl RenameToSpan;
		protected System.Web.UI.WebControls.Repeater CollectionRepeater;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			Privilege[] privs = new Privilege[] { 
				Privilege.DeleteCollection, Privilege.ManageCollection,
				Privilege.ModifyACL, Privilege.ManageControlledLists,
				Privilege.ModifyImages };
			ArrayList colls = new ArrayList();
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			foreach (Collection coll in Collection.GetCollections())
			{
				if (coll.Type == CollectionType.PersonalImages ||
					coll.Type == CollectionType.SharedImages)
				{
					if (user != null && user.Administrator)
						colls.Add(coll);
				}
				else
				{
					foreach (Privilege p in privs)
						if (Orciid.Core.User.HasPrivilege(p, coll))
						{
							colls.Add(coll);
							break;
						}
				}
				if (!IsPostBack && coll is NIXRemoteCollection)
				{
					AddNIXCollectionLinkButton.Enabled = false;
					// FogBugz case 553: cannot change the text of a link button like this
					AddNIXCollectionLinkButton.Text += " " + GetLocalString(this, "AlreadyExistsLabel", "(already exists)");
				}
			}
			
			CollectionRepeater.DataSource = colls;
			CollectionRepeater.DataBind();
			CreatePanel.Visible = Orciid.Core.User.HasPrivilege(Privilege.CreateCollection);
			CollectionGroupPanel.Visible = Orciid.Core.User.HasPrivilege(Privilege.ManageCollectionGroups);
			if (!IsPostBack)
			{
				ResourcePathTextBox.Text = Configuration.Instance.GetString("content.resourcepath");
				FillCollectionGroupListBox();
				TypeDropDownList.Items.Clear();
				TypeDropDownList.Items.Add(new ListItem(GetLocalString(this, "LocalTypeLabel", "Local"), "Internal"));
				TypeDropDownList.Items.Add(new ListItem(GetLocalString(this, "RemoteTypeLabel", "Remote"), "Remote"));
			}			
		}

		private void FillCollectionGroupListBox()
		{
			CollectionGroupListBox.Items.Clear();
			foreach (CollectionGroup group in CollectionGroup.GetCollectionGroups())
				CollectionGroupListBox.Items.Add(new ListItem(group.Title, group.ID.ToString()));
		}

		public override string GetHighlightedMenuItem()
		{
			return "Management_Collections";
		}

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return Orciid.Core.User.HasPrivilege(Privilege.CreateCollection, user) ||
				Orciid.Core.User.HasPrivilege(Privilege.ManageCollectionGroups, user) ||
				Orciid.Core.User.HasPrivilegeOnAny('C', user,
				Privilege.DeleteCollection, Privilege.ManageCollection, Privilege.ModifyACL);
		}
 
		#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.CreateButton.Click += new System.EventHandler(this.CreateButton_Click);
			this.AddNIXCollectionLinkButton.Click += new System.EventHandler(this.AddNIXCollectionLinkButton_Click);
			this.AddNewCollectionGroupButton.Click += new System.EventHandler(this.AddNewCollectionGroupButton_Click);
			this.RenameCollectionGroupButton.Click += new System.EventHandler(this.RenameCollectionGroupButton_Click);
			this.RemoveCollectionGroupButton.Click += new System.EventHandler(this.RemoveCollectionGroupButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void CreateButton_Click(object sender, System.EventArgs e)
		{
			string title = TitleTextBox.Text;
			string description = DescriptionTextBox.Text;
			string resourcepath = ResourcePathTextBox.Text;
//			string remoteurl = RemoteUrlTextBox.Text;
			string type = TypeDropDownList.SelectedValue;
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();
			if (title != null && title.Length > 0 &&
				description != null && description.Length > 0 &&
				resourcepath != null && resourcepath.Length > 0)
			{
				Collection coll;
				if (type == "Internal")
					coll = new Collection();
				else if (type == "Remote")
				{
					coll = new RemoteCollection();
//					((RemoteCollection)coll).RemoteUrl = remoteurl;
				}
				else
					throw new Exception("Invalid collection type");
				coll.Title = title;
				coll.Description = description;
				coll.ResourcePath = resourcepath;				
				ImageSettings settingsFull = new ImageSettings();
				settingsFull.width = 3000;
				settingsFull.height = 3000;
				settingsFull.quality = 100;
				settingsFull.fixedsize = false;
				coll.SetImageSettings(ImageSize.Full, settingsFull);
				ImageSettings settingsMedium = new ImageSettings();
				settingsMedium.width = 800;
				settingsMedium.height = 800;
				settingsMedium.quality = 90;
				settingsMedium.fixedsize = false;
				coll.SetImageSettings(ImageSize.Medium, settingsMedium);
				ImageSettings settingsThumbnail = new ImageSettings();
				settingsThumbnail.width = 96;
				settingsThumbnail.height = 72;
				settingsThumbnail.quality = 80;
				settingsThumbnail.fixedsize = true;
				coll.SetImageSettings(ImageSize.Thumbnail, settingsThumbnail);
				coll.Update();
				if (Orciid.Core.User.HasPrivilege(Privilege.ModifyACL, coll))
				{
					IAccessControl acl = coll.GetAccessControl();
					acl.AddUserPrivilege(coll.GetRelevantPrivileges(), Privilege.None, user.ID);
				}
				Response.Redirect(String.Format("collection.aspx?id={0}", coll.ID));
			}
			else
				ShowWarning(GetLocalString(this, "RequiredFieldsWarning", 
					"Please fill in all required fields to create a new collection."));
		}

		private void RemoveCollectionGroupButton_Click(object sender, System.EventArgs e)
		{
			if (CollectionGroupListBox.SelectedValue == "")
				ShowWarning(GetLocalString(this, "SelectGroupForRemoval",
					"Please select a collection group to remove."));
			else
			{
				try
				{
					CollectionGroup.GetByID(Int32.Parse(CollectionGroupListBox.SelectedValue)).Delete();
				}
				catch
				{
					ShowError(GetLocalString(this, "GroupRemovalFailed",
						"Removing collection group failed."));
				}
			}
		}

		private void AddNewCollectionGroupButton_Click(object sender, System.EventArgs e)
		{
			string s = AddNewCollectionGroupTextBox.Text.Trim();
			if (s == "")
				ShowWarning(GetLocalString(this, "EnterTitleForNewGroup",
					"Please enter a title for the collection group you want to add."));
			else
			{
				CollectionGroup g = new CollectionGroup();
				g.Title = s;
				g.Update();
				FillCollectionGroupListBox();
			}
		}

		private void RenameCollectionGroupButton_Click(object sender, System.EventArgs e)
		{
			string s = RenameCollectionGroupTextBox.Text.Trim();
			if (s == "")
				ShowWarning(GetLocalString(this, "EnterTitleForRenamedGroup",
					"Please enter a new title for the collection group you want to rename."));
			else if (CollectionGroupListBox.SelectedValue == "")
				ShowWarning(GetLocalString(this, "SelectGroupToRename",
					"Please select a collection group to rename."));
			else
			{
				CollectionGroup g = CollectionGroup.GetByID(Int32.Parse(CollectionGroupListBox.SelectedValue));
				g.Title = s;
				g.Update();
				FillCollectionGroupListBox();
			}		
		}

		private void AddNIXCollectionLinkButton_Click(object sender, System.EventArgs e)
		{
			Orciid.Core.User user = Orciid.Core.User.CurrentUser();			
			Collection coll = new NIXRemoteCollection();
			coll.Title = GetLocalString(this, "NIXCollectionTitle", "NASA Image eXchange (NIX)");
			coll.Description = GetLocalString(this, "NIXCollectionDescription", 
				"The NASA Image eXchange (NIX) is a web-based search engine for searching NASA's " +
				"online multimedia collections. Searching is performed using keywords. This service " +
				"is an initiative sponsored by the NASA STI Program toward linking many existing photo " +
				"databases in NASA. Currently, not all NASA photos are online, and not all NASA photo " +
				"databases are linked to NIX. Minimum technical standards for a photo database must " +
				"exist at a center for it to be linked to NIX. An Agency Subgroup is working to " +
				"increase the scope and number of photos in NIX. See http://nix.nasa.gov/ for more " +
				"information.");
			coll.ResourcePath = Path.Combine(Configuration.Instance.GetString("content.resourcepath"), "nix");
			ImageSettings settingsFull = new ImageSettings();
			settingsFull.width = 3000;
			settingsFull.height = 3000;
			settingsFull.quality = 100;
			settingsFull.fixedsize = false;
			coll.SetImageSettings(ImageSize.Full, settingsFull);
			ImageSettings settingsMedium = new ImageSettings();
			settingsMedium.width = 800;
			settingsMedium.height = 800;
			settingsMedium.quality = 90;
			settingsMedium.fixedsize = false;
			coll.SetImageSettings(ImageSize.Medium, settingsMedium);
			ImageSettings settingsThumbnail = new ImageSettings();
			settingsThumbnail.width = 96;
			settingsThumbnail.height = 72;
			settingsThumbnail.quality = 80;
			settingsThumbnail.fixedsize = true;
			coll.SetImageSettings(ImageSize.Thumbnail, settingsThumbnail);
			coll.Update();
			IAccessControl acl = coll.GetAccessControl();
			acl.AddUserPrivilege(coll.GetRelevantPrivileges(), Privilege.None, user.ID);
			Properties props = Properties.GetProperties(coll);
			props.Set("repimage", Request.Url.GetLeftPart(UriPartial.Authority) + 
				Request.ApplicationPath + (Request.ApplicationPath.EndsWith("/") ? "" : "/") +
				"plugins/nix/logo.jpg");
			Response.Redirect(String.Format("collection.aspx?id={0}", coll.ID));
		}
	}
}
