/*
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.Tasklist;
using Plumtree.Remote.PRC.Collaboration.Project;

	/// <summary>
	/// Summary description for TaskListSampleCS.
	/// </summary>
	public class TaskListSampleCS : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Literal TreeView;

		protected System.Web.UI.WebControls.Button go;
		protected System.Web.UI.WebControls.Panel CreateTaskList;
		protected System.Web.UI.WebControls.Panel CreateTaskListPanel;
		protected System.Web.UI.WebControls.TextBox TaskListName;
		protected System.Web.UI.WebControls.TextBox TaskListDescription;

		protected static string[] tasklistOptions = new string[] {"Create task list", 
																	 "Remove task list", 
																	 "Search task lists",
																	 "Create top-level task", 
																	 "Remove task", 
																	 "Search tasks", 
																	 "Create sub-task", 
																	 "Shows all task lists and tasks"} ;

		protected IProject sampleProject = null;

		protected IRemoteSession remoteSession;
		protected ICollaborationFactory collabFactory;
		protected System.Web.UI.WebControls.DropDownList OptionDropDownList;
		protected System.Web.UI.WebControls.Button CreateTaskListSubmit;
		protected static bool isLoaded;

		protected System.Web.UI.WebControls.Panel SearchTaskListsPanel;
		protected System.Web.UI.WebControls.TextBox SearchTaskListsProjectID;
		protected System.Web.UI.WebControls.LinkButton SearchSampleProjectLink;
		protected System.Web.UI.WebControls.Button SearchTaskListsInOtherProjectButton;
		protected System.Web.UI.WebControls.Panel CreateTopLevelTaskPanel;
		protected System.Web.UI.WebControls.TextBox TaskName;
		protected System.Web.UI.WebControls.TextBox ContainingTaskListID;
		protected System.Web.UI.WebControls.TextBox TaskDescription;
		protected System.Web.UI.WebControls.Button CreateTopLevelTaskButton;
		protected System.Web.UI.WebControls.Panel RemoveTaskPanel;
		protected System.Web.UI.WebControls.TextBox RemoveTaskID;
		protected System.Web.UI.WebControls.Button RemoveTaskButton;
		protected System.Web.UI.WebControls.Panel SearchTasksPanel;
		protected System.Web.UI.WebControls.TextBox SearchTasksTaskListID;
		protected System.Web.UI.WebControls.Button SearchTasksButton;
		protected System.Web.UI.WebControls.Panel RemoveTaskListPanel;
		protected System.Web.UI.WebControls.TextBox RemoveTaskListID;
		protected System.Web.UI.WebControls.Button RemoveSubmitButton;
		protected System.Web.UI.WebControls.Panel CreateSubTaskPanel;
		protected System.Web.UI.WebControls.TextBox SubTaskParentTaskID;
		protected System.Web.UI.WebControls.TextBox SubTaskName;
		protected System.Web.UI.WebControls.TextBox SubTaskDescription;
		protected System.Web.UI.WebControls.Button CreateSubTaskButton;

		protected ITaskListManager tasklistManager;

	
		private void Page_Load(object sender, System.EventArgs e)
		{
			IPortletContext portletContext = PortletContextFactory.CreatePortletContext(Request, Response);
			remoteSession = portletContext.GetRemotePortalSession();
			
			collabFactory = remoteSession.GetCollaborationFactory();
			tasklistManager = collabFactory.GetTaskListManager();

			sampleProject = (IProject)Session["edk_sample_project"];

			if(sampleProject == null)
				Response.Redirect("../project/ProjectCreatorCS.aspx?source=../tasklist/TaskListSampleCS.aspx");

			sampleProject = (IProject)Session["edk_sample_project"];

			if (!isLoaded || OptionDropDownList == null || OptionDropDownList.SelectedIndex == -1)
			{
				OptionDropDownList.DataSource = tasklistOptions;		
				OptionDropDownList.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);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.go.Click += new System.EventHandler(this.Button1_Click);
			this.CreateTaskListSubmit.Click += new System.EventHandler(this.Submit_Click);
			this.RemoveSubmitButton.Click += new System.EventHandler(this.RemoveSubmitButton_Click);
			this.SearchTaskListsInOtherProjectButton.Click += new System.EventHandler(this.SearchTaskListsInOtherProjectButton_Click);
			this.SearchSampleProjectLink.Click += new System.EventHandler(this.SearchSampleProjectLink_Click);
			this.CreateTopLevelTaskButton.Click += new System.EventHandler(this.CreateTopLevelTaskButton_Click);
			this.RemoveTaskButton.Click += new System.EventHandler(this.RemoveTaskButton_Click);
			this.SearchTasksButton.Click += new System.EventHandler(this.SearchTasksButton_Click);
			this.CreateSubTaskButton.Click += new System.EventHandler(this.CreateSubTaskButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void Button1_Click(object sender, System.EventArgs e)
		{
			//Create task list
			if (OptionDropDownList.SelectedIndex == 0)
			{
				CreateTaskListPanel.Visible = true;
				CreateTaskListPanel.Enabled = true;
			}
				//Remove task list
			else if (OptionDropDownList.SelectedIndex == 1)
			{
				RemoveTaskListPanel.Visible = true;
				RemoveTaskListPanel.Enabled = true;
			}
				//Search task lists
			else if (OptionDropDownList.SelectedIndex == 2)
			{
				SearchTaskListsPanel.Visible = true;
				SearchTaskListsPanel.Enabled = true;
			}
				//Create top-level tasks
			else if (OptionDropDownList.SelectedIndex == 3)
			{
				CreateTopLevelTaskPanel.Visible = true;
				CreateTopLevelTaskPanel.Enabled = true;
			}
				//Remove task 
			else if (OptionDropDownList.SelectedIndex == 4)
			{
				RemoveTaskPanel.Visible = true;
				RemoveTaskPanel.Enabled = true;
			}
				//Search tasks 
			else if (OptionDropDownList.SelectedIndex == 5)
			{
				SearchTasksPanel.Visible = true;
				SearchTasksPanel.Enabled = true;
			}
				//Create sub-task 
			else if (OptionDropDownList.SelectedIndex == 6)
			{
				CreateSubTaskPanel.Visible = true;
				CreateSubTaskPanel.Enabled = true;
			}
				//Show all task lists and tasks 
			else if (OptionDropDownList.SelectedIndex == 7)
			{
				ShowAll();
			}
		}

		private void Submit_Click(object sender, System.EventArgs e)
		{
			this.CreateTaskListPanel.Visible = true;
			string name = (null == TaskListName.Text) ? "SampleTaskList" : TaskListName.Text;
			string description  = (null == TaskListDescription.Text) ? "SampleTaskListDescription" : TaskListDescription.Text;

			ITaskList tasklist = null;
			if (sampleProject != null)
			{
				tasklist = CreateAndStoreTaskList(sampleProject, name, description);

				StringBuilder html = new StringBuilder();
				html.Append("Created task list has name=");
				html.Append(tasklist.Name);
				html.Append(", ID=");
				html.Append(tasklist.ID);
				html.Append(" [<a href=\"" + tasklist.DetailsURL + "\">");
				html.Append("details");
				html.Append("</a>]");
				html.Append("<br/>");
				Response.Write(html.ToString());
				this.CreateTaskListPanel.Visible = false;
			}
		}


		private void RemoveSubmitButton_Click(object sender, System.EventArgs e)
		{
			ITaskList tasklist = null;
			int tasklistID = -1;

			try
			{
				tasklistID = Int32.Parse(RemoveTaskListID.Text);
			
				tasklist = tasklistManager.GetTaskList(tasklistID);
				if(tasklist == null)
				{
					Response.Write("Could not find task list with ID : " + tasklistID);
				}
			}
			catch (FormatException)
			{
				Response.Write("Cannot parse task list ID: [" + RemoveTaskListID.Text + "]");
			}

			if (tasklist != null)
			{
				StringBuilder html = new StringBuilder();

				if (RemoveTasklist(tasklist))
				{
					html.Append("Task list with ID=");
					html.Append(tasklistID);
					html.Append(" removed.");
				}
				else
				{
					html.Append("Failed to remove task list with ID : ");
					html.Append(tasklistID);
					html.Append(".");
				}
				Response.Write(html.ToString());
			}
			this.RemoveTaskListPanel.Visible = false;
		}


		// core helper functions

		//creates a task list
		public ITaskList CreateAndStoreTaskList(IProject project, String name, String description)
		{
			ITaskList tasklist = tasklistManager.CreateTaskList(project, name, description);
			//call Store() to persist to the task list
			tasklist.Store();
			return tasklist;
		}

		//removes a task list
		public bool RemoveTasklist(ITaskList tasklist)
		{
			bool removed = false;
			int tasklistID = tasklist.ID;
			tasklistManager.RemoveTaskList(tasklist);
      
			// trying to retrieve the task list after removal, should retrieve nothing
			ITaskList taskListAfterRemoval = tasklistManager.GetTaskList(tasklistID);
			if (taskListAfterRemoval == null)
			{
				removed = true;
			}
			else
			{
				removed = false;
			}
			return removed;
		}

		//creates a task
		public ITask CreateAndStoreTopLevelTask(ITaskList tasklist, String name, String description, DateTime startTime, DateTime endTime)
		{
			ITask task = tasklist.CreateTask(name, description, startTime, endTime);
			//If you want to set additional properties, make sure that Store() is called, otherwise the changes will not be persisted.
			//For example,
			task.Notes = "Notes for sample TopLevel Task";
			task.Risk = TaskRisks.Medium;
			task.Status = TaskStatuses.Pending;
     
			//call Store() to persist to the task
			task.Store();
			return task;
		}

		//creates a sub-task
		public ITask CreateAndStoreSubTask(ITask parentTask, String name, String description, DateTime startTime, DateTime endTime)
		{
			//CreateSubTask() will create a persisted task, so
			//Store() does not need to be called to persist the task properties unless additional properties are set.
			ITask subtask = parentTask.CreateSubTask(name, description, startTime, endTime);
      
			//If you want to set additional properties, make sure that Store() is called, otherwisethe changes will not be persisted.
			subtask.Risk = TaskRisks.Low;
			subtask.Status = TaskStatuses.FiftyPercentCompleted;
     
			//call Store() to persist to the addditional properties set on the sub-task
			subtask.Store();
			return subtask;
		}

		//removes a task 
		public bool RemoveTask(ITask task)
		{
			bool removed = false;
			int taskID = task.ID;
			
			ITaskList tasklist = task.ContainingTaskList;
			if (tasklist == null)
			{
				removed = false;
			}
			else
			{
				tasklist.RemoveTask(task);

				// trying to retrieve the task after removal, should retrieve nothing
				ITask taskAfterRemoval = tasklistManager.GetTask(taskID);
				if (taskAfterRemoval == null)
				{
					removed = true;
				}
				else
				{
					removed = false;
				}
			}
			return removed;
		}

		//search all task lists in a project with default tasklist filter
		public ITaskList[] GetTaskLists(IProject project) 
		{
			ITaskListFilter filter = tasklistManager.CreateTaskListFilter();
			ITaskList[] children = tasklistManager.QueryTaskLists(project, filter);
			return children;
		}

		//search all task lists in a task list with default task filter
		public ITask[] GetTasks(ITaskList tasklist) 
		{
			ITaskFilter filter = tasklistManager.CreateTaskFilter();
			ITask[] tasks = tasklistManager.QueryTasks(tasklist, filter);
			return tasks;
		}

		public void ShowAll()
		{
			ITaskList[] tasklists = GetTaskLists(sampleProject);
			TreeView = new Literal();
			TreeView.Text = "";
			for (int i = 0; i < tasklists.Length; i++) 
			{
				TreeView.Text += AppendTasklist(tasklists[i]).Text;
			}
			Response.Write(TreeView.Text);
		}

		public LiteralControl AppendTasklist(ITaskList tasklist)
		{
			if(tasklist == null)
				return null;

			StringBuilder html = new StringBuilder();
			html.Append(tasklist.Name);
			html.Append(" (id=");
			html.Append(tasklist.ID);
			html.Append(")");
			html.Append(" [<a href=\"" + tasklist.DetailsURL + "\">");
			html.Append("details");
			html.Append("</a>]");
			html.Append("<br/>");
			LiteralControl rv = new LiteralControl(html.ToString());

			ITask[] childTasks = GetTasks(tasklist);
			for(int i = 0; i < childTasks.Length; i++)
				rv.Text += AppendTask(childTasks[i]).Text;
			return rv;
		}

		public LiteralControl AppendTask(ITask task)
		{
			StringBuilder html = new StringBuilder();
			
			html.Append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
			html.Append("-" + task.Name);
			html.Append(" (id=");
			html.Append(task.ID);
			html.Append(")");

			html.Append(" [<a href=\"" + task.DetailsURL + "\">");
			html.Append("details");
			html.Append("</a>]");
			html.Append("<br/>");
			LiteralControl rv = new LiteralControl(html.ToString());
			return rv;
		}

		private void SearchTaskListsInOtherProjectButton_Click(object sender, System.EventArgs e)
		{
			this.SearchTaskListsPanel.Visible = true;
			IProject project = null;
			int projectID = -1;

			try
			{
				projectID = Int32.Parse(SearchTaskListsProjectID.Text);
			
				project = collabFactory.GetProjectManager().GetProject(projectID);
				if(project == null)
				{
					Response.Write("Could not find project with ID: " + projectID);
				}
			}
			catch (FormatException)
			{
				Response.Write("Cannot parse project ID: [" + SearchTaskListsProjectID.Text + "]");
			}
			RenderTaskLists(project);
		}

		private void SearchSampleProjectLink_Click(object sender, System.EventArgs e)
		{
			RenderTaskLists(sampleProject);
		}

		private void RenderTaskLists(IProject project)
		{
			if (project != null)
			{
				ITaskList[] tasklists = GetTaskLists(project);

				StringBuilder html = new StringBuilder();

				if (tasklists.Length > 0)
				{
					html.Append("Project with name=");
					html.Append(project.Name);
					html.Append(", ID=");
					html.Append(project.ID);
					html.Append(" has ");
					html.Append(tasklists.Length);
					html.Append(" tasklists.");
					html.Append("<br/>");
					html.Append("<br/>");

					//now print out all searched task lists
					for (int i = 0; i < tasklists.Length; i++)
					{
						html.Append(i);
						html.Append(". ");
						html.Append(tasklists[i].Name);
						html.Append(" (id=");
						html.Append(tasklists[i].ID);
						html.Append(") [<a href=\"" + tasklists[i].DetailsURL + "\">");
						html.Append("details");
						html.Append("</a>]");
						html.Append("<br/>");
					}					
				}
				else
				{
					html.Append("No task lists found in project with ID : ");
					html.Append(project.ID);
					html.Append(".");
				}
				Response.Write(html.ToString());
			}
			this.SearchTaskListsPanel.Visible = false;
		}

		private void CreateTopLevelTaskButton_Click(object sender, System.EventArgs e)
		{
			int tasklistID = -1;
			ITaskList tasklist = null;
			try
			{
				tasklistID = Int32.Parse(ContainingTaskListID.Text);
			
				tasklist = tasklistManager.GetTaskList(tasklistID);
				if(tasklist == null)
				{
					Response.Write("Could not find task list with ID: " + tasklistID);
				}
			}
			catch (FormatException)
			{
				Response.Write("Cannot parse task list ID: [" + ContainingTaskListID.Text + "]");
			}

			string name = (null == TaskName.Text) ? "SampleTask" : TaskName.Text;
			string description  = (null == TaskDescription.Text) ? "SampleTaskDescription" : TaskDescription.Text;

			ITask task = null;
			if (tasklist != null)
			{
				task = CreateAndStoreTopLevelTask(tasklist, name, description, new DateTime(), new DateTime());

				StringBuilder html = new StringBuilder();
				html.Append("Created task has name=");
				html.Append(task.Name);
				html.Append(", ID=");
				html.Append(task.ID);
				html.Append(" [<a href=\"" + task.DetailsURL + "\">");
				html.Append("details");
				html.Append("</a>]");
				html.Append("<br/>");
				Response.Write(html.ToString());
				this.CreateTopLevelTaskPanel.Visible = false;
			}
			this.CreateTopLevelTaskPanel.Visible = false;
		}

		private void RemoveTaskButton_Click(object sender, System.EventArgs e)
		{
			this.RemoveTaskPanel.Visible = true;
			ITask task = null;
			int taskID = -1;

			try
			{
				taskID = Int32.Parse(RemoveTaskID.Text);
			
				task = tasklistManager.GetTask(taskID);
				if(task == null)
				{
					Response.Write("Could not find task with ID : " + taskID);
				}
			}
			catch (FormatException)
			{
				Response.Write("Cannot parse task ID: [" + RemoveTaskID.Text + "]");
			}

			if (task != null)
			{
				StringBuilder html = new StringBuilder();

				if (RemoveTask(task))
				{
					html.Append("Task with ID=");
					html.Append(taskID);
					html.Append(" removed.");
				}
				else
				{
					html.Append("Failed to remove task with ID=");
					html.Append(taskID);
					html.Append(".");
				}
				Response.Write(html.ToString());
			}

			this.RemoveTaskPanel.Visible = false;

		}

		private void SearchTasksButton_Click(object sender, System.EventArgs e)
		{
			this.SearchTasksPanel.Visible = true;
			ITaskList tasklist = null;
			int tasklistID = -1;

			try
			{
				tasklistID = Int32.Parse(SearchTasksTaskListID.Text);
			
				tasklist = tasklistManager.GetTaskList(tasklistID);
				if(tasklist == null)
				{
					Response.Write("Could not find task list with ID : " + tasklistID);
				}
			}
			catch (FormatException)
			{
				Response.Write("Cannot parse task list ID: [" + SearchTasksTaskListID.Text + "]");
			}

			if (tasklist != null)
			{
				ITask[] tasks = GetTasks(tasklist);

				StringBuilder html = new StringBuilder();

				if (tasks.Length > 0)
				{
					html.Append("Task list with name=");
					html.Append(tasklist.Name);
					html.Append(", ID=");
					html.Append(tasklist.ID);
					html.Append(" has ");
					html.Append(tasks.Length);
					html.Append(" tasks.");
					html.Append("<br/>");
					html.Append("<br/>");

					//now print out all searched task lists
					for (int i = 0; i < tasks.Length; i++)
					{
						html.Append(i);
						html.Append(". ");
						html.Append(tasks[i].Name);
						html.Append(" (id=");
						html.Append(tasks[i].ID);
						html.Append(") [<a href=\"" + tasks[i].DetailsURL + "\">");
						html.Append("details");
						html.Append("</a>]");
						html.Append("<br/>");
					}					
				}
				else
				{
					html.Append("No tasks found in task list with ID : ");
					html.Append(tasklist.ID);
					html.Append(".");
				}
				Response.Write(html.ToString());
			}
			this.SearchTasksPanel.Visible = false;
		}

		private void CreateSubTaskButton_Click(object sender, System.EventArgs e)
		{
			int parentTaskID = -1;
			ITask parentTask = null;
			try
			{
				parentTaskID = Int32.Parse(SubTaskParentTaskID.Text);
			
				parentTask = tasklistManager.GetTask(parentTaskID);
				if(parentTask == null)
				{
					Response.Write("Could not find task with ID: " + parentTaskID);
				}
			}
			catch (FormatException)
			{
				Response.Write("Cannot parse task ID: [" + SubTaskParentTaskID.Text + "]");
			}

			string name = (null == SubTaskName.Text) ? "SampleTask" : SubTaskName.Text;
			string description  = (null == SubTaskDescription.Text) ? "SampleTaskDescription" : SubTaskDescription.Text;

			ITask subTask = null;
			if (parentTask != null)
			{
				subTask = CreateAndStoreSubTask(parentTask, name, description, new DateTime(), new DateTime());

				StringBuilder html = new StringBuilder();
				html.Append("Created sub-task has name=");
				html.Append(subTask.Name);
				html.Append(", ID=");
				html.Append(subTask.ID);
				html.Append(" [<a href=\"" + subTask.DetailsURL + "\">");
				html.Append("details");
				html.Append("</a>]");
				html.Append("<br/>");
				Response.Write(html.ToString());
			}
			this.CreateSubTaskPanel.Visible = false;
		}

}
