<%
/*
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.
*/
%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.plumtree.remote.prc.collaboration.*,
				com.plumtree.remote.prc.collaboration.project.*, 
				com.plumtree.remote.prc.collaboration.tasklist.*, 	
				com.plumtree.remote.portlet.*, 
				java.util.*" %>
				
<%!
	
	//gets the tasklist manager
	private ITaskListManager getTaskListManager(HttpServletRequest req, HttpServletResponse res, JspWriter pout) throws Exception 
	{
		ITaskListManager tasklistManager = null;
		IPortletContext portletContext = PortletContextFactory.createPortletContext(req, res);
		IPortletRequest portletRequest = portletContext.getRequest();
		String loginToken = portletRequest.getLoginToken();
		if (null == loginToken)
		{
			pout.println("Unable to retrieve the login token. Confirm that the login token has been checked in the Advanced Settings page of the Web Service.");
		}
		//get the remote session
		com.plumtree.remote.prc.IRemoteSession portalSession = portletContext.getRemotePortalSession();

		//get a collab factory and a project manager
		ICollaborationFactory collabFactory = portalSession.getCollaborationFactory();
		tasklistManager = collabFactory.getTaskListManager();
		return tasklistManager;
	}
	
	private ITaskList getTaskList(int tasklistID, ITaskListManager tasklistManager) throws Exception
	{
		//ask for a tasklist to create the top level task in
		ITaskList tasklist = tasklistManager.getTaskList(tasklistID);
		//squawk if the tasklist could not be retrieved
		return tasklist;
	}
	
    public ITask[] getChildTasks(ITaskList tasklist, ITaskListManager manager) throws Exception
    {
        ITaskFilter filter = manager.createTaskFilter();
        ITask[] children = manager.queryTasks(tasklist, filter);
        return children;
    }	
	
	public void renderTask(ITask task, ITaskListManager manager, JspWriter out, int depth) throws Exception
    {
        for(int i = 0; i < depth; i++)
            out.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        out.write("- " + task.getName() + " (id=" + task.getID() + ")");
        out.write(" [<a href=\"" + task.getDetailsURL() + "\">");
        out.write("details");
        out.write("</a>]");
        out.write("<br/>");
    }

    public void renderTaskList(ITaskList tasklist, ITaskListManager manager, JspWriter out, int depth) throws Exception
    {
        if(tasklist == null)
            return;

        for(int i = 0; i < depth; i++)
            out.write("&nbsp;&nbsp;&nbsp;");
        out.write(tasklist.getName() + " (id=" + tasklist.getID() + ")");        
        out.write(" [<a href=\"" + tasklist.getDetailsURL() + "\">");
        out.write("details");
        out.write("</a>]");
        out.write("<br/>");

        ITask[] childTasks = getChildTasks(tasklist, manager);
        for(int i = 0; i < childTasks.length; i++)
            renderTask(childTasks[i], manager, out, depth + 1);
    }
	
	
  //creates and persists a task list
  public static ITaskList createAndStoreTaskList(IProject project, String name, String description, ITaskListManager tasklistManager) throws Exception
  {
      ITaskList tasklist = tasklistManager.createTaskList(project, name, description);     
      //call store() to persist to task list
      tasklist.store();
      return tasklist;
  }

  
  //creates and persists a toplevel task
  public static ITask createAndStoreTopLevelTask(ITaskList tasklist, String name, String description, Date startTime, Date endTime, ITaskListManager tasklistManager) throws Exception
  {
      //create the task
      ITask task = tasklist.createTask(name, description, startTime, endTime);
      //call store() to persist the task 
      task.store();
      return task;
  }
  
  //creates and persists a subtask
  public static ITask createAndStoreSubTask(ITask parentTask, String name, String description, Date startTime, Date endTime) throws Exception
  {
      //create the subtask; 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);      
      //call store() to persist the subtask 
      subtask.store();
      return subtask;
  }
      
  //removes a task list
  public static boolean removeTasklist(ITaskList tasklist, ITaskListManager tasklistManager) throws Exception
  {
      boolean removed = false;
      int tasklistID = tasklist.getID();
      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;
  }

  //removes a task 
  public static boolean removeTask(ITask task, JspWriter out, ITaskListManager tasklistManager) throws Exception
  {
  	  	boolean removed = false;
      	int taskID = task.getID();
      	ITaskList tasklist = task.getContainingTaskList();
     	if (tasklist == null)
      	{
      		out.write("Unable to remove task with id=" + task.getID() + " - Fail to retrieve its containing task list."); 	  
 	  		removed = false;     
		}
		else
		{     
	      // if tasklist can be retrieved, proceed with remove 	
	      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;
  }
%>

<%
IProject sampleProject = null;

//booleans for different tasklist sample options -  create, remove and search, and showAll
boolean createTaskList = false;
boolean removeTaskList = false;
boolean searchTaskLists = false;

boolean createTask = false;
boolean removeTask = false;
boolean searchTasks = false;

boolean createSubTask = false;
boolean showAll = false;

//optional name and description for create
String name = request.getParameter("name");
String description = request.getParameter("description");

//tasklist and task id required for remove
int tasklistID = -1;
int taskID = -1;

//determine which option we are using- create, remove, or search.
String select = request.getParameter("tasklistMethod");
if (null != select)
{
	if (select.equals("createTaskList"))
	{
	  createTaskList = true;
	}
	else if (select.equals("removeTaskList"))  
	{
	  removeTaskList = true;
	}
	else if (select.equals("searchTaskLists"))
	{
	  searchTaskLists = true;
	}
	else if (select.equals("createTask"))
	{
	  createTask = true;
	}
	else if (select.equals("removeTask"))  
	{
	  removeTask = true;
	}
	else if (select.equals("searchTasks"))
	{
	  searchTasks = true;
	}
	else if (select.equals("createSubTask"))
	{
	  createSubTask = true;
	}
	else if (select.equals("showAll"))
	{
		showAll = true;
	}
	
}

//if any of these is true, set hosted display mode
if (createTaskList || removeTaskList || searchTaskLists || createTask || removeTask || searchTasks || createSubTask || showAll)
{
		IPortletContext portletContext = PortletContextFactory.createPortletContext(request, response);
		IPortletResponse portletResponse = portletContext.getResponse();
		portletResponse.setHostedDisplayMode(HostedDisplayMode.Hosted);        
}

//see if we have a tasklist id- if so, convert it to an int.
String strTaskListID = request.getParameter("tasklistID");
if (null != strTaskListID)
{
 try
 {
 	tasklistID = Integer.parseInt(strTaskListID); 
 }
 catch (Exception e) 
 {
  out.println("Unable to parse tasklistID of " + strTaskListID); 
 } 
} 

//see if we have a task id- if so, convert it to an int.
String strTaskID = request.getParameter("taskID");
if (null != strTaskID)
{
 try
 {
 	taskID = Integer.parseInt(strTaskID); 
 }
 catch (Exception e) 
 {
  out.println("Unable to parse taskID of " + strTaskID); 
 } 
} 



  
%>


<table>
<form name="selectForm" method="POST" action="tasklistExample.jsp">
<tr>
<td>
<!--select for create, remove, search-->
<select name="tasklistMethod">
<option value="createTaskList" <% if(createTaskList)out.println(" SELECTED ");%>>Create task list</option>
<option value="removeTaskList" <% if(removeTaskList)out.println(" SELECTED ");%>>Remove task list</option>
<option value="searchTaskLists" <% if(searchTaskLists)out.println(" SELECTED ");%>>Search task lists</option>
<option value="createTask" <% if(createTask)out.println(" SELECTED ");%>>Create top-level task</option>
<option value="removeTask" <% if(removeTask)out.println(" SELECTED ");%>>Remove task</option>
<option value="searchTasks" <% if(searchTasks)out.println(" SELECTED ");%>>Search tasks</option>
<option value="createSubTask" <% if(createSubTask)out.println(" SELECTED ");%>>Create sub-task</option>
<option value="showAll" <% if(showAll)out.println(" SELECTED ");%>>Show all task lists and tasks</option>


</select>
<input type="submit" name="selectGo" value="go"/>

</td>
</tr>


<%
	//attempt to retrieve the sample project; if not found, create it, then redirect back to the current page    
    sampleProject = (IProject) session.getAttribute("edk_sample_project");
    if(sampleProject == null)
    {
    	response.sendRedirect("../project/ProjectCreator.jsp");
    }
%>


<!--show a search box for search, and a box to box to enter the project id if remove-->
<% 
if (createTaskList)
{
  //if no name or description, show text boxes for name and description, and a submit button
  if (null == name || null == description)
  {
    %>
	<tr>
	 <td>
	   Task List Name:
	 </td>
	 <td>
	   <input type="text" name="name" value="<%=(null==name)?"":name%>"/>
	 </td>
	</tr>
	<tr>
	 <td>
	   Task List Description:
	 </td>
	 <td>
	   <input type="text" name="description" value="<%=(null==description)?"":description%>"/>
	 </td>
	</tr>	
	<tr>
	 <td>
	   <input type="submit" name="createSubmit" value="submit"/>
	 </td>
	</tr>		
   <%
  }
  else
  //create a project and print out the project id
  {
		name = (null == name) ? "ExampleTaskList" : name;
		description = (null == description) ? "ExampleTaskListDescription" : description;
		
		//create the task list
		ITaskListManager tasklistManager = getTaskListManager(request, response, out);
		ITaskList tasklist = createAndStoreTaskList(sampleProject, name, description, tasklistManager);

		//if you want to set additional properties, make sure that store() is called or the changes will not be persisted.
		//for example:
		//tasklist.setDefaultSecurity(false);
		//tasklist.setAccessLevel(RoleType.MEMBER, AccessLevel.EDIT);
		
		//store() needs to be called to persist the changes 
		//tasklist.store();

		%>
		<tr>
			<td>
			<%
				out.println("\nCreated task list has name=" + tasklist.getName() + ", ID=" +  tasklist.getID());
			%>
			</td>
		</tr>    
  <%
  }
}
if (removeTaskList)
{
	//if no tasklist ID, add a text box for tasklistID, and a submit button
	if (tasklistID == -1)
	{
		%>
		<tr>
			<td>
				Task List ID:
			</td>
			<td>
				<input type="text" name="tasklistID" value="<%=(null==strTaskListID)?"":strTaskListID%>"/>
			</td>
		</tr>	
		<tr>
			<td>
				<input type="submit" name="removeSubmit" value="submit"/>
			</td>
		</tr>
		<%
		} 
		else
		{
		//remove the tasklist
		ITaskListManager tasklistManager = getTaskListManager(request, response, out);
		ITaskList tasklist = tasklistManager.getTaskList(tasklistID);
		//squawk if the tasklist could not be retrieved
		if (null == tasklist)
		{
			%>
			<tr>
				<td>
					<%out.println("Unable to retrieve tasklist with ID of " + tasklistID);%>
				</td>
			</tr>

			<%
		}
		else
		{
			//remove
			boolean removed = removeTasklist(tasklist, tasklistManager);
			if (removed)
			{ 			
			%>
			<tr>
				<td>
					<%out.println("Task list with id of " + tasklistID + " removed.");%>
				</td>
			</tr>
			<%
			}
			else
			{
			%>
			<tr>
				<td>
					<%out.println("Failed to remove task list with id of " + tasklistID + ".");%>
				</td>
			</tr>			
			<%
			}
		}
	}
}

if (searchTaskLists)
{
	//perform the search
	ITaskListManager tasklistManager = getTaskListManager(request, response, out);
	ITaskListFilter tasklistFilter = tasklistManager.createTaskListFilter();
	
    //Different options can be set to search on task lists that contain only PENDING tasks, 
    //completed tasks, or overdue tasks.  See documentation in TaskListCompletionFilterType, for example
    //tasklistFilter.setCompletionType(TaskListCompletionFilterType.COMPLETED);
    
          
    //You can limit the return results, for example:
    //tasklistFilter.setMaximumResults(10);
      
    //You can also disable security checking on the returned objects against the user who performs this query, 
    //so that all objects will be returned
    tasklistFilter.setRestoreSecurity(false);
      
    //You can use TaskListQueryOrder to sort the query result; 
    //for example, below TaskListQueryOrder shows sorting the returned task lists by NAME in ascending order
    //TaskListQueryOrder taskListQueryOrder = new TaskListQueryOrder(TaskListAttribute.NAME, true);
    //taskListFilter.setQueryOrders(new TaskListQueryOrder[] {taskListQueryOrder} );
      
	//query on all tasklists using default filter values, and print out the results
	ITaskList[] tasklists = tasklistManager.queryTaskLists(sampleProject, tasklistFilter);
	if (tasklists.length > 0)
	{
	%>			
		<tr>
			<td>
				Search Results
			</td>
			
		</tr>
		<tr>
			<td>
				Task List Name
			</td>
		<td>
			Task List ID
		</td>
			</tr>
		<%
		for (int i = 0; i < tasklists.length; i++)
		{
			ITaskList tasklist = tasklists[i];
			%>
			<tr>
				<td>
			  		<%out.println(tasklist.getName());%>
				</td>
				<td>
					<%out.println(tasklist.getID());%>
				</td>
			</tr>
			<%	
		}
	}
	else
	{
		%>
		<tr>
			<td colspan="2">
				<%out.println("No tasklists found using search query of " + "searchText");%>
			</td>
		</tr>
		<%
	}
}
if (showAll)
{
	//perform the search
	ITaskListManager tasklistManager = getTaskListManager(request, response, out);
	ITaskListFilter tasklistFilter = tasklistManager.createTaskListFilter();
	
	//do not set any limit on the filter; by default it will return all results	
	ITaskList[] tasklists = tasklistManager.queryTaskLists(sampleProject, tasklistFilter);
	if (tasklists.length > 0)
	{
		out.write("You can click on the details link below to get to the actual tasklist or task.");
		out.write("<br/>");
		out.write("<br/>");
		
		for (int i = 0; i < tasklists.length; i++)
		{
			ITaskList tasklist = tasklists[i];		
			renderTaskList(tasklists[i], tasklistManager, out, 0); 			
		}
	}
	else
	{
		%>
		<tr>
			<td colspan="2">
				<%out.println("No tasklists found in project.");%>
			</td>
		</tr>
		<%
	}
}
if (createTask)
{
	//ask for a tasklist to create the top level task in
    %>
	<tr>
		<td>
			Task List ID:
		</td>
		<td>
			<input type="text" name="tasklistID" value="<%=(null==strTaskListID)?"":strTaskListID%>"/>
		</td>
	</tr>	
	<%
		
  //if no name or description, show text boxes for name and description, and a submit button	
  if (null == name || null == description)
  {  
    %>
	<tr>
	 <td>
	   Task Name:
	 </td>
	 <td>
	   <input type="text" name="name" value="<%=(null==name)?"":name%>"/>
	 </td>
	</tr>
	<tr>
	 <td>
	   Task Description:
	 </td>
	 <td>
	   <input type="text" name="description" value="<%=(null==description)?"":description%>"/>
	 </td>
	</tr>	
	<tr>
	 <td>
	   <input type="submit" name="createSubmit" value="submit"/>
	 </td>
	</tr>		
   <%
  }
  else
  //create a task and print out the task id
  {
		name = (null == name) ? "ExampleTask" : name;
		description = (null == description) ? "ExampleTaskDescription" : description;
		
		//create the task
		ITaskListManager tasklistManager = getTaskListManager(request, response, out);
		ITaskList tasklist = tasklistManager.getTaskList(tasklistID);
		//squawk if the tasklist could not be retrieved
		if (null == tasklist)
		{
			%>
			<tr>
				<td>
					<%out.println("Unable to retrieve tasklist with ID of " + tasklistID);%>
				</td>
			</tr>
			<%
		}
		else
		{		
			ITask task = createAndStoreTopLevelTask(tasklist, name, description, new Date(), new Date(), tasklistManager);
	
			//if you want to set additional properties, make sure that store() is called or the changes will not be persisted.
			//for example:
			//task.setRisk(TaskRisk.HIGH);
			//task.setNotes("Task Notes");
			//task.setStatus(TaskStatus.FIFTY_PERCENT_COMPLETED);
			
			//store() needs to be called to persist the changes 
			//task.store();
	
			%>
			<tr>
				<td>
				<%
					out.println("\nCreated task has name=" + task.getName() + ", ID=" +  task.getID());
				%>
				</td>
			</tr>    
	  		<%
	  }
  }
}
if (removeTask)
{
	//if no task ID, add a text box for taskID, and a submit button
	if (taskID == -1)
	{
		%>
		<tr>
			<td>
				Task ID:
			</td>
			<td>
				<input type="text" name="taskID" value="<%=(null==strTaskID)?"":strTaskID%>"/>
			</td>
		</tr>	
		<tr>
			<td>
				<input type="submit" name="removeSubmit" value="submit"/>
			</td>
		</tr>
		<%
		} 
		else
		{
		//remove the task
		ITaskListManager tasklistManager = getTaskListManager(request, response, out);
		ITask task = tasklistManager.getTask(taskID);
		//squawk if the task could not be retrieved
		if (null == task)
		{
			%>
			<tr>
				<td>
					<%out.println("Unable to retrieve task with ID of " + taskID);%>
				</td>
			</tr>
			<%
		}
		else
		{
			//remove
			boolean removed = removeTask(task, out, tasklistManager);
			if (removed)
			{ 			
			%>
			<tr>
				<td>
					<%out.println("Task with id of " + taskID + " removed.");%>
				</td>
			</tr>
			<%
			}
			else
			{
			%>
			<tr>
				<td>
					<%out.println("Failed to remove task with id of " + taskID + ".");%>
				</td>
			</tr>			
			<%
			}
		}
	}
}
if (searchTasks)
{
	ITaskListManager tasklistManager = getTaskListManager(request, response, out);
	ITaskFilter taskFilter = tasklistManager.createTaskFilter();

    //Different options include searching for COMPLETED tasks, OVERDUE tasks, or PENDING tasks
    //see documentation in TaskCompletionFilterType, for example:
    //taskFilter.setCompletionType(TaskCompletionFilterType.ALL);
          
    //You can also limit the return results, for example, the following will limit the max result to be 10 
    //taskFilter.setMaximumResults(10);
      
    //You can also disable security checking on the returned objects against the user who performs this query, 
    //so that all objects will be returned
    //taskFilter.setRestoreSecurity(false);
      
    //You can use TaskQueryOrder to sort the query result; below TaskQueryOrder shows sorting the returned task lists by NAME in ascending order
    //TaskQueryOrder taskQueryOrder = new TaskQueryOrder(TaskAttribute.NAME, true);
    //taskFilter.setQueryOrders(new TaskQueryOrder[] {taskQueryOrder} );

	//query on all tasks in the project using default filter values
	ITask[] tasks = tasklistManager.queryTasks(sampleProject, taskFilter);
	if (tasks.length > 0)
	{
	%>			
		<tr>
			<td>
				Search Results
			</td>
			
		</tr>
		<tr>
			<td>
				Task Name
			</td>
		<td>
			Task ID
		</td>
			</tr>
		<%
		for (int i = 0; i < tasks.length; i++)
		{
			ITask task = tasks[i];
			%>
			<tr>
				<td>
			  		<%out.println(task.getName());%>
				</td>
				<td>
					<%out.println(task.getID());%>
				</td>
			</tr>
			<%	
		}
	}
	else
	{
		%>
		<tr>
			<td colspan="2">
				<%out.println("No tasks found in the sample project.");%>
			</td>
		</tr>
		<%
	}
}
if (createSubTask)
{
	//ask for parent task for creating the sub-task 
    %>
	<tr>
		<td>
			Parent Task ID:
		</td>
		<td>
			<input type="text" name="taskID" value="<%=(null==strTaskID)?"":strTaskID%>"/>
		</td>
	</tr>	
	<%
		
  //if no name or description, show text boxes for name and description, and a submit button	
  if (null == name || null == description)
  {  
    %>
	<tr>
	 <td>
	   Sub-task Name:
	 </td>
	 <td>
	   <input type="text" name="name" value="<%=(null==name)?"":name%>"/>
	 </td>
	</tr>
	<tr>
	 <td>
	   Sub-task Description:
	 </td>
	 <td>
	   <input type="text" name="description" value="<%=(null==description)?"":description%>"/>
	 </td>
	</tr>	
	<tr>
	 <td>
	   <input type="submit" name="createSubmit" value="submit"/>
	 </td>
	</tr>		
   <%
  }
  else
  //create a sub-task and print out the sub-task id
  {
		name = (null == name) ? "ExampleSubTask" : name;
		description = (null == description) ? "ExampleSubTaskDescription" : description;
		
		//create the sub-task
		ITaskListManager tasklistManager = getTaskListManager(request, response, out);
		ITask parentTask = tasklistManager.getTask(taskID);
		//squawk if the parent task could not be retrieved
		if (null == parentTask)
		{
			%>
			<tr>
				<td>
					<%out.println("Unable to retrieve task with ID of " + taskID);%>
				</td>
			</tr>
			<%
		}
		else
		{		
			ITask subTask = createAndStoreSubTask(parentTask, name, description, new Date(), new Date());
	
			//if you want to set additional properties, make sure that store() is called or the changes will not be persisted.
			//for example:
			//subTask.setRisk(TaskRisk.HIGH);
			//subTask.setNotes("Task Notes");
			//subTask.setStatus(TaskStatus.FIFTY_PERCENT_COMPLETED);
			
			//store() needs to be called to persist the changes 
			//subTask.store();
	
			%>
			<tr>
				<td>
				<%
					out.println("Created sub-task has name=" + subTask.getName() + ", ID=" +  subTask.getID());
				%>
				</td>
			</tr>    
	  		<%
	  }
  }
}

%>
</form>
</table>


