/*
Copyright (c) 2003, Plumtree Software

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1.  Neither the name of Plumtree Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission; 

2.  Licensee acknowledges that no license or other permission is granted herein with respect to any third party software and that Licensee may not use the code in any way that would infringe any third party right.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, NONINFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. REGARDLESS OF THE BASIS OF RECOVERY CLAIMED, WHETHER UNDER ANY CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE AND STRICT LIABILITY), BREACH OF STATUTORY DUTY, PRINCIPLES OF CONTRIBUTION OR 
ANY OTHER THEORY OF LIABILITY, IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE; AND IN NO EVENT WILL THE COPYRIGHT OWNER'S OR CONTRIBUTORS' EXCEED $10,000.
*/

 
using System;
using System.Text;
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 Plumtree.Remote.Portlet;
using IRemoteSession = Plumtree.Remote.PRC.IRemoteSession;
using ICollaborationFactory = Plumtree.Remote.PRC.Collaboration.ICollaborationFactory;
using RemoteSessionFactory = Plumtree.Remote.PRC.RemoteSessionFactory;

using Plumtree.Remote.PRC.Collaboration;
using Plumtree.Remote.PRC.Collaboration.Security;
using Plumtree.Remote.PRC.Collaboration.Project;


	/// <summary>
	/// Summary description for SecurityExampleCS.
	/// </summary>
public class SecurityExampleCS : System.Web.UI.Page
{

	protected static string[] SecurityOptions = 
		new string[] {"Add member", 
					  "Remove member", 
				      "Retrieve members",
					  "Set security for a functional area"} ;

	protected static string[] RoleTypeOptions = new string[] {"Member", "Guest"} ;
	protected static string[] RetrieveRoleTypeOptions = new string[] {"Member", "Guest", "Leader"} ;

	protected static string[] FunctionalAreaOptions = 
		new string[] {"Discussion",  
					  "Document", 
				      "Document Folder",
					  "Project",
					  "Task List"} ;

	protected static string[] AccessLevelOptions = 
		new string[] {"Admin",  
						 "Edit", 
						 "Write",
						 "Read",
						 "None"} ;

	protected IProject sampleProject = null;
	protected static bool isLoaded = false;

	protected IRemoteSession remoteSession;
	protected ICollaborationFactory collabFactory;
	protected IProjectManager projectManager;
	protected System.Web.UI.WebControls.DropDownList AddMemberDropDownList;
	protected System.Web.UI.WebControls.Button AddMemberButton;
	protected System.Web.UI.WebControls.Panel AddMemberPanel;
	protected System.Web.UI.WebControls.Panel RemoveMemberPanel;
	protected System.Web.UI.WebControls.DropDownList SecurityOptionsDropDownList;
	protected System.Web.UI.WebControls.DropDownList RemoveMemberDropDownList;
	protected System.Web.UI.WebControls.TextBox RemoveMemberIDInput;
	protected System.Web.UI.WebControls.Button RemoveMemberButton;
	protected System.Web.UI.WebControls.Button DropDownButton;
	protected System.Web.UI.WebControls.Panel RetrieveMembersPanel;
	protected System.Web.UI.WebControls.DropDownList RetrieveMembersDropDownList;
	protected System.Web.UI.WebControls.Button RetrieveMembersButton;
	protected System.Web.UI.WebControls.Panel SetSecurityPanel;
	protected System.Web.UI.WebControls.DropDownList SetSecurityRoleTypeDropDownList;
	protected System.Web.UI.WebControls.DropDownList FunctionalAreaDropDownList;
	protected System.Web.UI.WebControls.DropDownList AccessLevelDropDownList;
	protected System.Web.UI.WebControls.Button SetSecurityButton;
	protected System.Web.UI.WebControls.TextBox AddMemberIDInput;
	
	private void Page_Load(object sender, System.EventArgs e)
	{
		IPortletContext portletContext = PortletContextFactory.CreatePortletContext(Request, Response);
		remoteSession = portletContext.GetRemotePortalSession();
	
		collabFactory = remoteSession.GetCollaborationFactory();
		projectManager = collabFactory.GetProjectManager();

		sampleProject = (IProject)Session["edk_sample_project"];
		if(sampleProject == null)
			Response.Redirect("../project/ProjectCreatorCS.aspx?source=../security/SecurityExampleCS.aspx");

		if (!isLoaded || SecurityOptionsDropDownList == null || SecurityOptionsDropDownList.SelectedIndex == -1)
		{
			SecurityOptionsDropDownList.DataSource = SecurityOptions;
			SecurityOptionsDropDownList.DataBind();  //binds the data
			isLoaded = true;
		}
		GetPostBackEventReference(this);
	}

	#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);
		SecurityOptionsDropDownList.DataSource = SecurityOptions;
		SecurityOptionsDropDownList.DataBind();  //binds the data

	}
		
	/// <summary>
	/// Required method for Designer support - do not modify
	/// the contents of this method with the code editor.
	/// </summary>
	private void InitializeComponent()
	{    
		this.AddMemberButton.Click += new System.EventHandler(this.AddMemberButton_Click);
		this.RemoveMemberButton.Click += new System.EventHandler(this.RemoveMemberButton_Click);
		this.DropDownButton.Click += new System.EventHandler(this.DropDownButton_Click);
		this.RetrieveMembersButton.Click += new System.EventHandler(this.RetrieveMembersButton_Click);
		this.SetSecurityButton.Click += new System.EventHandler(this.SetSecurityButton_Click);
		this.Load += new System.EventHandler(this.Page_Load);

	}
	#endregion

	private void DropDownButton_Click(object sender, System.EventArgs e)
	{
		//Add Member
		if (SecurityOptionsDropDownList.SelectedIndex == 0)
		{
			AddMemberPanel.Visible = true;
			AddMemberPanel.Enabled = true;
			AddMemberDropDownList.DataSource = RoleTypeOptions;
			AddMemberDropDownList.DataBind();
		}
		//Remove Member
		else if (SecurityOptionsDropDownList.SelectedIndex == 1)
		{
			RemoveMemberPanel.Visible = true;
			RemoveMemberPanel.Enabled = true;
			RemoveMemberDropDownList.DataSource = RoleTypeOptions;
			RemoveMemberDropDownList.DataBind();
		}
		//Retrieve Members
		else if (SecurityOptionsDropDownList.SelectedIndex == 2)
		{
			RetrieveMembersPanel.Visible = true;
			RetrieveMembersPanel.Enabled = true;
			RetrieveMembersDropDownList.DataSource = RetrieveRoleTypeOptions;
			RetrieveMembersDropDownList.DataBind();
		}
		//Set security for a functional area
		else if (SecurityOptionsDropDownList.SelectedIndex == 3)
		{
			SetSecurityPanel.Visible = true;
			SetSecurityPanel.Enabled = true;
			SetSecurityRoleTypeDropDownList.DataSource = RoleTypeOptions;
			SetSecurityRoleTypeDropDownList.DataBind();
			FunctionalAreaDropDownList.DataSource = FunctionalAreaOptions;
			FunctionalAreaDropDownList.DataBind();
			AccessLevelDropDownList.DataSource = AccessLevelOptions;
			AccessLevelDropDownList.DataBind();
		}
		GetPostBackEventReference(this);
	}

	private void AddMemberButton_Click(object sender, System.EventArgs e)
	{
		RoleTypes roleType = RoleTypes.Member;
		int addMemberID = -1;

		if (AddMemberDropDownList.SelectedIndex == 0)
		{
			roleType = RoleTypes.Member;
		}
		else if (AddMemberDropDownList.SelectedIndex == 1)
		{
			roleType = RoleTypes.Guest;
		}

		try
		{
			addMemberID = Int32.Parse(AddMemberIDInput.Text);
		}
		catch (FormatException error)
		{
			//for invalid input ID, print out error message and abort
			Response.Write("Cannot parse add member ID: [" + AddMemberIDInput.Text + "]");
			AddMemberPanel.Visible = false;
			return;
		}

		//for valid Member ID
		IRole role = null;
		if (sampleProject == null)
			Response.Redirect("../project/ProjectCreatorCS.aspx?source=../security/SecurityExampleCS.aspx");

		if (sampleProject != null)
		{
			role = sampleProject.GetRole(roleType);
			role.AddMember(addMemberID, MemberTypes.User);
			try 
			{
				role.Store();
			}
			catch (Exception error)
			{
				//failed to add non-negative ID, print out error message and abort
				Response.Write("Failed to add member with id=" + addMemberID + " to role. <br/> Cause of error is: ");
				Response.Write(error.Message);
				AddMemberPanel.Visible = false;
				return;
			}

			int[] memberIDs = role.GetMemberIDs(MemberQueryTypes.AllUsers);

			StringBuilder html = new StringBuilder();
			html.Append("Updated role ");
			html.Append(role.Name);
			html.Append(" - added user with ID=");
			html.Append(addMemberID);
			html.Append(".");
			html.Append("<br/>");
			html.Append("Now the role has ");
			html.Append(memberIDs.Length);
			html.Append(" members.");
			html.Append("<br/> <br/>");
				
			for (int i = 0 ; i < memberIDs.Length; i++)
			{
				html.Append("<br/>");
				html.Append("memberIDs[");
				html.Append(i);
				html.Append("] is ");
				html.Append(memberIDs[i]);
			}
			Response.Write(html.ToString());
		}
		AddMemberPanel.Visible = false;
	}

	private void RemoveMemberButton_Click(object sender, System.EventArgs e)
	{
		RoleTypes roleType = RoleTypes.Member;
		int removeMemberID = -1;

		if (RemoveMemberDropDownList.SelectedIndex == 0)
		{
			roleType = RoleTypes.Member;
		}
		else if (RemoveMemberDropDownList.SelectedIndex == 1)
		{
			roleType = RoleTypes.Guest;
		}

		try
		{
			removeMemberID = Int32.Parse(RemoveMemberIDInput.Text);
		}
		catch (FormatException error)
		{
			//for invalid input ID, print out error message and abort
			Response.Write("Cannot parse remove member ID: [" + RemoveMemberIDInput.Text + "]");
			RemoveMemberPanel.Visible = false;
			return;
		}

		//for valid Member ID
		IRole role = null;
		if (sampleProject == null)
			Response.Redirect("../project/ProjectCreatorCS.aspx?source=../security/SecurityExampleCS.aspx");

		if (sampleProject != null)
		{
			role = sampleProject.GetRole(roleType);
			role.RemoveMember(removeMemberID, MemberTypes.User);
			try 
			{
				role.Store();
			}
			catch (Exception error)
			{
				//failed to remove non-negative ID, print out error message and abort
				Response.Write("Failed to remove member with id=" + removeMemberID + ". <br/> Cause of error is: ");
				Response.Write(error.Message);
				RemoveMemberPanel.Visible = false;
				return;
			}

			int[] memberIDs = role.GetMemberIDs(MemberQueryTypes.AllUsers);

			StringBuilder html = new StringBuilder();
			html.Append("Updated role ");
			html.Append(role.Name);
			html.Append(" - removed user with ID : ");
			html.Append(removeMemberID);
			html.Append(".");
			html.Append("<br/>");
			html.Append("Now the role has ");
			html.Append(memberIDs.Length);
			html.Append(" members.");
			html.Append("<br/> <br/>");
				
			for (int i = 0 ; i < memberIDs.Length; i++)
			{
				html.Append("<br/>");
				html.Append("memberIDs[");
				html.Append(i);
				html.Append("] is ");
				html.Append(memberIDs[i]);
			}
			Response.Write(html.ToString());
		}
		RemoveMemberPanel.Visible = false;
	}

	private void RetrieveMembersButton_Click(object sender, System.EventArgs e)
	{
		RoleTypes roleType = RoleTypes.Member;
		
		if (RetrieveMembersDropDownList.SelectedIndex == 0)
		{
			roleType = RoleTypes.Member;
		}
		else if (RetrieveMembersDropDownList.SelectedIndex == 1)
		{
			roleType = RoleTypes.Guest;
		}
		else if (RetrieveMembersDropDownList.SelectedIndex == 2)
		{
			roleType = RoleTypes.Leader;
		}

		//for valid Member ID
		IRole role = null;
		if (sampleProject == null)
			Response.Redirect("../project/ProjectCreatorCS.aspx?source=../security/SecurityExampleCS.aspx");

		if (sampleProject != null)
		{
			role = sampleProject.GetRole(roleType);
			int[] memberIDs = role.GetMemberIDs(MemberQueryTypes.AllUsers);

			StringBuilder html = new StringBuilder();
			html.Append(role.Name);
			html.Append(" has ");
			html.Append(memberIDs.Length);
			html.Append(" members.");
			html.Append("<br/> <br/>");
				
			for (int i = 0 ; i < memberIDs.Length; i++)
			{
				html.Append("<br/>");
				html.Append("memberIDs[");
				html.Append(i);
				html.Append("] is ");
				html.Append(memberIDs[i]);
			}
			Response.Write(html.ToString());
		}
		RetrieveMembersPanel.Visible = false;	
	}

	private void SetSecurityButton_Click(object sender, System.EventArgs e)
	{
		//get role type information
		RoleTypes roleType = RoleTypes.Member;		
		if (SetSecurityRoleTypeDropDownList.SelectedIndex == 0)
		{
			roleType = RoleTypes.Member;
		}
		else if (SetSecurityRoleTypeDropDownList.SelectedIndex == 1)
		{
			roleType = RoleTypes.Guest;
		}

		//get functional area information
		FunctionalAreas functionalArea = FunctionalAreas.Discussion;
		if (FunctionalAreaDropDownList.SelectedIndex == 0)
		{
			functionalArea = FunctionalAreas.Discussion;
		}
		else if (FunctionalAreaDropDownList.SelectedIndex == 1)
		{
			functionalArea = FunctionalAreas.Document;
		}
		else if (FunctionalAreaDropDownList.SelectedIndex == 2)
		{
			functionalArea = FunctionalAreas.DocumentFolder;
		}
		else if (FunctionalAreaDropDownList.SelectedIndex == 3)
		{
			functionalArea = FunctionalAreas.Project;
		}
		else if (FunctionalAreaDropDownList.SelectedIndex == 4)
		{
			functionalArea = FunctionalAreas.TaskList;
		}

		//get functional area information
		AccessLevels accessLevel = AccessLevels.Admin;
		if (AccessLevelDropDownList.SelectedIndex == 0)
		{
			accessLevel = AccessLevels.Admin;
		}
		else if (AccessLevelDropDownList.SelectedIndex == 1)
		{
			accessLevel = AccessLevels.Edit;
		}
		else if (AccessLevelDropDownList.SelectedIndex == 2)
		{
			accessLevel = AccessLevels.Write;
		}
		else if (AccessLevelDropDownList.SelectedIndex == 3)
		{
			accessLevel = AccessLevels.Read;
		}
		else if (AccessLevelDropDownList.SelectedIndex == 4)
		{
			accessLevel = AccessLevels.None;
		}

		IRole role = null;
		if (sampleProject == null)
			Response.Redirect("../project/ProjectCreatorCS.aspx?source=../security/SecurityExampleCS.aspx");

		if (sampleProject != null)
		{
			role = sampleProject.GetRole(roleType);
			role.SetAccessLevel(functionalArea, accessLevel);
			try 
			{
				role.Store();
			}
			catch (Exception error)
			{
				//failed to remove non-negative ID, print out error message and abort
				Response.Write("Failed to set security for function area=" + functionalArea + ", with access level=" + accessLevel + ". <br/> Cause of error is: ");
				Response.Write(error.Message);
				SetSecurityPanel.Visible = false;
				return;
			}

			StringBuilder html = new StringBuilder();
			html.Append("Updated role ");
			html.Append(role.Name);
			html.Append(" with access level set to ");
			html.Append(role.GetAccessLevel(functionalArea));
			html.Append(" for ");
			html.Append(functionalArea);
			html.Append(". ");
			html.Append("<br/> <br/>");
			Response.Write(html.ToString());
		}
		SetSecurityPanel.Visible = false;
	}
}
