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.Web.Caching;
using System.Xml;
using System.Runtime.Remoting.Messaging;
using System.IO;
using Orciid.Core;

namespace Orciid
{
	public class collectionsharing : PageTemplate.OrciidPage
	{
		protected System.Web.UI.WebControls.Label CollectionTitleLabel;
		protected System.Web.UI.WebControls.HyperLink PropertiesHyperLink;
		protected System.Web.UI.WebControls.DataGrid SharingDataGrid;
		
		private Collection coll;
		protected System.Web.UI.HtmlControls.HtmlGenericControl Heading;
		private ArrayList entryIDs;

		private void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack)
			{
				try
				{
					coll = Collection.GetByID(Int32.Parse(Request.QueryString["id"]));
				}
				catch
				{
					coll = null;
				}
				CheckAuthorization();
				PropertiesHyperLink.NavigateUrl = String.Format("collection.aspx?id={0}", coll.ID);
				CollectionTitleLabel.Text = coll.Title;
				DataBind();
			}
		}

		public override void DataBind()
		{
			ArrayList entries = new ArrayList();
			entries.AddRange(coll.GetShareEntries());
			entryIDs = new ArrayList();
			foreach (CollectionShareEntry entry in entries)
				entryIDs.Add(entry.ID);
			entries.Add(coll.CreateShareEntry());
			SharingDataGrid.DataSource = entries;
			SharingDataGrid.EditItemIndex = entries.Count - 1;
			SharingDataGrid.DataBind();
		}

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

		protected override bool CheckUserPrivileges(Orciid.Core.User user)
		{
			return true;
		}
 
		protected override void LoadViewState(object savedState) 
		{
			if (savedState != null)
			{
				base.LoadViewState(savedState);
				coll = null;
				if (ViewState["cid"] != null)
					coll = Collection.GetByID((int)ViewState["cid"]);
				entryIDs = ViewState["entryIDs"] as ArrayList;
				CheckAuthorization();
			}
		}

		protected override object SaveViewState()
		{
			if (coll != null)
				ViewState["cid"] = coll.ID;
			ViewState["entryIDs"] = entryIDs;
			return base.SaveViewState();
		}

		private void CheckAuthorization()
		{
			Privilege[] privs = new Privilege[] { Privilege.ModifyACL };
			bool authorized = false;
			if (coll != null)
			{
				foreach (Privilege p in privs)
					if (Orciid.Core.User.HasPrivilege(p, coll))
					{
						authorized = true;
						break;
					}
			}
			if (!authorized)
				Response.Redirect("insufficientprivileges.aspx"); 
		}

		#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.SharingDataGrid.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.SharingDataGrid_UpdateCommand);
			this.SharingDataGrid.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.SharingDataGrid_DeleteCommand);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void SharingDataGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			foreach (CollectionShareEntry entry in coll.GetShareEntries())
				if (entry.ID == (int)entryIDs[e.Item.ItemIndex])
				{
					entry.Delete();
					break;
				}
			DataBind();
		}

		private void SharingDataGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			try
			{
				CollectionShareEntry entry = coll.CreateShareEntry();
				entry.User = ((TextBox)e.Item.Cells[0].FindControl("UserTextBox")).Text;
				entry.Subnet = ((TextBox)e.Item.Cells[1].FindControl("SubnetTextBox")).Text;
				entry.Mask = ((TextBox)e.Item.Cells[2].FindControl("MaskTextBox")).Text;
				entry.CacheTimeSpan = Int32.Parse(((TextBox)e.Item.Cells[3].FindControl("CacheTimeSpanTextBox")).Text);
				entry.ExpirationTimeSpan = Int32.Parse(((TextBox)e.Item.Cells[4].FindControl("ExpirationTimeSpanTextBox")).Text);
				entry.SearchResults = Int32.Parse(((TextBox)e.Item.Cells[5].FindControl("SearchResultsTextBox")).Text);
				entry.Update();
				DataBind();
			}
			catch (Exception ex)
			{
				TransactionLog.Instance.AddException("Handled Exception", "Collection Sharing", ex);
				this.ShowError(ex.Message);
			}
		}

	}
}
