<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.net.URL,
				 java.util.*,
				 java.text.SimpleDateFormat,
                 java.io.PrintWriter,
                 java.util.StringTokenizer,
                 com.plumtree.remote.portlet.*,
                 com.plumtree.remote.prc.*,
                 com.plumtree.remote.prc.content.*,
                 com.plumtree.remote.prc.content.dataentrytemplate.*,
                 com.plumtree.remote.prc.content.folder.*,
                 com.plumtree.remote.prc.content.property.*,
                 com.plumtree.remote.prc.content.selectionlist.*,
                 com.plumtree.remote.prc.content.item.*"
%>
<%
    PrintWriter jspOut = response.getWriter();
    
    IPortletContext portletContext = null;
    IRemoteSession remoteSession = null;
    IDataEntryTemplate dataEntryTemplate = null;
    
    try
    {
		portletContext = PortletContextFactory.createPortletContext(request, response);
		remoteSession = portletContext.getRemotePortalSession();

		//Get the content factory.
		IContentFactory contentFactory = remoteSession.getContentFactory();

		//Get the folder containing the data entry template.
		IFolder folder = retrieveContentFolder(contentFactory);

		//Get the data entry template
		dataEntryTemplate = retrieveDET(contentFactory, folder);
		
		Map parameterMap = request.getParameterMap();
		String[] contentItemTest = (String[])parameterMap.get("Content Item Name");
		if(null != contentItemTest && contentItemTest.length > 0)
		{
			//If we got the content item name in the request parameters we'll assume
			//this request was from the create content item button.  So we'll handle it first.
			handleCreateButtonClick(remoteSession, dataEntryTemplate, jspOut, parameterMap);
					
		}
    }
    catch(Exception ex)
    {
    	jspOut.println("<font color='#ff0000'>Exception: " + ex.getMessage() + "</font><br>");
    }
%>
<%!
	/**
	 * Gets the Content Server folder used to store the Content
	 * Server objects for our application.
	 * <p>
	 * In this sample, we will create a new folder.  In your
	 * real application you would likely have created the folder
	 * already and will need to query for it here.
	 */
	private static IFolder retrieveContentFolder(IContentFactory factory) throws Exception
	{
		// Get a folder manager for working with Content Server folders.
		IFolderManager folderManager = factory.getFolderManager();
		
		//Check to see if the folder has already been created
		IFolder subFolder = folderManager.getFolderByPath("/Java Web Example - DET");
		
		if(subFolder == null)
		{
			//If the folder is not there we will create our own folder for the sample

			// Get a reference to the root folder.  It always exists.
			IFolder rootFolder = folderManager.getRootFolder();

			// Create a new folder
			subFolder = folderManager.createFolder(rootFolder, "Java Web Example - DET");
			subFolder.store();
		}
		return subFolder;
	}

	
	/**
		 * Gets the DET that defines what fields are present in each
		 * customer support incident.
		 * <p>
		 * In this sample, we will create a new DET.  In your real
		 * application, this method would probably query an already
		 * existing DET.
		 */
		private static IDataEntryTemplate retrieveDET(IContentFactory factory, IFolder folder) throws Exception
		{
			//
			// A Data Entry Template object is a collection of
			// property objects.  Each property object represents
			// a field in the records associated with the DET.
			//
			// This sample uses all of the classes of properties
			// available in Content Server.  Each customer support
			// incidents will have:
			//   (integer)         Incident ID
			//   (boolean)         If the incident has been resolved
			//   (float)           Incident severity rating
			//   (date)            Date the incident was opened
			//   (text line)       Customer name
			//   (item reference)  Link to other content item representing the customer
			//   (selection list)  The product the incident was reported in
			//   (text block)      Reported problem
			//   (file)            Logs of problem
			//   (image)           Screen shot of problem
			//
	
			// Get manager objects needed for creating a DET.
			IDataEntryTemplateManager detManager = factory.getDataEntryTemplateManager();
			
			// Check to see if the data entry template already exists
			IDataEntryTemplate det = detManager.getDataEntryTemplate(folder, "Support Incident Data Entry Template");
			if(det != null)
			{
				return det;
			}
			
			IPropertyManager propertyManager = factory.getPropertyManager();
			ISelectionListManager slManager = factory.getSelectionListManager();
	
			// Create a DET object.
			det = detManager.createDataEntryTemplate(folder, "Support Incident Data Entry Template");
			
			// Add an integer property.
			IIntegerProperty incident = propertyManager.createIntegerProperty("Incident ID", "The ticket number for this incident.");
			det.addProperty(incident);
			
			// Add a boolean property
			IBooleanProperty resolved = propertyManager.createBooleanProperty("Resolved", "True if the incident has been closed; false if it is still open.");
			det.addProperty(resolved);
			
			// Add a float property.
			IDoubleProperty severity = propertyManager.createDoubleProperty("Severity", "Percentage stating how severe the incident is.");
			det.addProperty(severity);
	
			// Add a date property.
			IDateProperty opened = propertyManager.createDateProperty("Date Opened", "The date and time the incident was reported.");
			det.addProperty(opened);
			
			// Add a text line property.
			//  Text lines are brief strings without newline characters.
			//  Use the text block property for storing longer strings.
			ITextLineProperty customerName = propertyManager.createTextLineProperty("Customer Name", "The name of the customer.");  
			det.addProperty(customerName);
			
			// Add an item reference property.
			//  An item reference links to another content item.  The
			//  content item does not have to be associated with the
			//  same DET.  For example, we will link to a fictional
			//  content item representing the customer that is having
			//  the support problem; which would be associated with
			//  a DET representing customers.
			//
			//  Not shown is the item collection property.  It is
			//  similar to the item reference property, but links to
			//  multiple content items.
			IItemReferenceProperty customerData = propertyManager.createItemReferenceProperty("Customer Information", "Links to information about the customer such as the contact and their phone number.");
			det.addProperty(customerData);
			
			// Add a selection list property.
			//  A selection list is a defined set of choices of which
			//  one may be selected.  This can be visualized as a
			//  drop down box.
			
			//Check to see if the selection list already exists
			ISelectionList selectionList = null;
			ISelectionList[] selectionLists = slManager.getSelectionLists(folder);
			for(int i = 0; i < selectionLists.length; i++)
			{
				if(selectionLists[i].getName().equals("Products Selection List"))
				{
					selectionList = selectionLists[i];
					break;
				}
			}
						
			if(selectionList == null)
			{
				String[] listValues = {"Portal", "Search Server", "Collaboration Server", "Content Server", "Analytics"};
				selectionList = slManager.createSelectionList(folder, "Products Selection List", listValues);
				selectionList.store();
			}
			
			ISelectionListProperty products = propertyManager.createSelectionListProperty("Product", "The product which the support incident is opened against", selectionList);
			det.addProperty(products);   
			
			// Add a text block property.
			//  Text block properties are used to store long strings
			//  that can span many lines.  For short strings contained
			//  on only one line, use the text line property instead.
			ITextBlockProperty description = propertyManager.createTextBlockProperty("Incident Description", "A writeup summarizing the problem the customer is experiencing.");
			det.addProperty(description);
			
			// Add a file property.
			IFileProperty log = propertyManager.createFileProperty("Log File", "A log file taken while the problem occurred.");
			det.addProperty(log);
	
			// Add an image property.
			IImageProperty screenShot = propertyManager.createImageProperty("Screen Shot", "A screen shot of the problem.");
			det.addProperty(screenShot);
	
			// Actually store the DET and all the properties associated with it.
			det.store();
			
			return det;
	}
	
	
	// Create all the controls for a given Data Entry Template.  The type of
	// control depends on the type of property.
	private String renderDataEntryTemplate(IDataEntryTemplate dataEntryTemplate) throws Exception
	{
		if(dataEntryTemplate == null)
			return "";
		
		StringBuffer buf = new StringBuffer();
		
		//create new table
		buf.append("<table id='Main DET Table' border='0'>");

		//add text input to enter Content Item Name
		buf.append(createTableRow("Content Item Name", "<input name='Content Item Name' type='text' id='Content Item Name' />", ""));
		
		//Loop through all the properties and add them to the table based on property type
		IBaseProperty[] allProperties = dataEntryTemplate.getAllProperties();
		for(int i = 0; i < allProperties.length; i++)
		{
			IBaseProperty property = allProperties[i];
			
			// Check for different types of properties
			if(property instanceof com.plumtree.remote.prc.content.property.IBooleanProperty)
			{
				String control = "<input id='" + property.getName() + "' type='checkbox' name='" + property.getName() + "' />";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.IDateProperty)
			{
				String control = "<input id='" + property.getName() + "' type='text' name='" + property.getName() + "' />";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.IDoubleProperty)
			{
				String control = "<input id='" + property.getName() + "' type='text' name='" + property.getName() + "' />";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.IFileProperty)
			{
				String control = "<input id='" + property.getName() + "' type='file' name='" + property.getName() + "' />";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.IImageProperty)
			{
				String control = "<input id='" + property.getName() + "' type='file' name='" + property.getName() + "' />";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.IIntegerProperty)
			{
				String control = "<input id='" + property.getName() + "' type='text' name='" + property.getName() + "' />";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.IItemReferenceProperty)
			{
				//We could query for valid content items and display them in a control
				//or display content items based on some other business logic.
				//For the sample we'll leave this blank.
				String control = "";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.ISelectionListProperty)
			{
				StringBuffer control = new StringBuffer();
				control.append("<select name='"+ property.getName() + "' id='" + property.getName() + "'>");

				ISelectionList selectionList = ((ISelectionListProperty)property).getSelectionList();
				String[] values = selectionList.getValues();
				for(int j = 0; j < values.length; j++)
				{
					control.append("<option value='" + values[j] + "'>" + values[j] + "</option>");		
				}
			
				buf.append(createTableRow(property.getDisplayName(), control.toString(), property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.ITextBlockProperty)
			{
				String control = "<textarea name='" + property.getName() + "' id='" + property.getName() + "'></textarea>";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			else if(property instanceof com.plumtree.remote.prc.content.property.ITextLineProperty)
			{
				String control = "<input id='" + property.getName() + "' type='text' name='" + property.getName() + "' />";

				buf.append(createTableRow(property.getDisplayName(), control, property.getDescription()));
			}
			
		}
		
		buf.append("</table>");
		
		return buf.toString();
	}
	
	// Create a content property row for the html table
	private static String createTableRow(String name, String control, String description)
	{
		StringBuffer buf = new StringBuffer();

		//Add Name to first column of first row
		buf.append("<tr>");
		buf.append("<td style='font-weight:bold;'>" + name + "</td>");
		
		//Add Control to second column of first row
		buf.append("<td>" + control + "</td>");
		buf.append("</tr>");
		
		//add description to second column of second row so
		//it is under the control
		buf.append("<tr><td></td><td>" + description + "</td></tr>");
		
		return buf.toString();
	}
	
	// Handle the create button click
	private void handleCreateButtonClick(IRemoteSession remoteSession, IDataEntryTemplate dataEntryTemplate, PrintWriter out, Map parameterMap)
	{
		try
		{
			//Get the Content Item Manager
			IContentFactory contentFactory = remoteSession.getContentFactory();		
			IContentItemManager contentItemManager = contentFactory.getContentItemManager();

			// Create a new Content Item.
			String contentItemName = ((String[])parameterMap.get("Content Item Name"))[0];
			IContentItem contentItem = contentItemManager.createContentItem(
												dataEntryTemplate.getContainingFolder(),
												contentItemName, 
												dataEntryTemplate);
			
			// Assign the fields of the content item.
			// Each field is defined by the DET corresponding to the content item.
			IBaseProperty[] props = dataEntryTemplate.getAllProperties();
				
			
			//NOTE: Even though renderDataEntryTemplate dynamically creates
			//controls for any data entry template, this method has been hard-coded 
			//for the data entry template we've created in retrieveDET for simplicity.
						
			Iterator it = parameterMap.keySet().iterator();
			while(it.hasNext())
			{
				String key = (String)it.next();
				String value = ((String[])parameterMap.get(key))[0];
				
				if(key.equals("Incident ID"))
				{
					contentItem.setIntegerPropertyValue(props[0], Integer.parseInt(value));
				}
				else if(key.equals("Resolved"))
				{
					contentItem.setBooleanPropertyValue(props[1], !value.equals("0"));
				}
				else if(key.equals("Severity"))
				{
					contentItem.setDoublePropertyValue(props[2], Double.parseDouble(value));
				}
				else if(key.equals("Date Opened"))
				{
					SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");	
					contentItem.setDatePropertyValue(props[3], formatter.parse(value));
				}
				else if(key.equals("Severity"))
				{
					contentItem.setDoublePropertyValue(props[2], Double.parseDouble(value));
				}
				else if(key.equals("Customer Name"))
				{
					contentItem.setTextLinePropertyValue(props[4], value);
				}
				else if(key.equals("Customer Information"))
				{
					//IContentItem customer = contentItemManager.getContentItem(dataEntryTemplate.getContainingFolder(), "Customer X");
					//contentItem.setItemReferencePropertyValue(props[5], customer);
				}
				else if(key.equals("Product"))
				{
					contentItem.setSelectionListPropertyValue(props[6], value);
				}
				else if(key.equals("Incident Description"))
				{
					contentItem.setTextBlockPropertyValue(props[7], value);
				}
				else if(key.equals("Log File"))
				{
					//get file from Request object...
					//contentItem.setFilePropertyValue(props[8], fileName, fileStream);
				}
				else if(key.equals("Screen Shot"))
				{
					//get file from Request object...
					//contentItem.setImagePropertyValue(props[9], fileName, fileStream);
				}		
			}
			
												
			//Store the content Item
			contentItemManager.checkInItem(contentItem, "Created by DET Sample Portlet");

			//Display a message about the new content item
			out.println("Content Item " + contentItemName + " Created<br>");
		}
		catch(Exception ex)
		{
			out.println("<font color='#ff0000'>Exception: " + ex.getMessage() + "</font><br>");
		}
	}
%>

<HTML>
	<HEAD>
		<title>Data Entry Template Sample</title>
	</HEAD>
	<body>
		<!-- Add the attribute enctype="multipart/form-data" to the form to enable file submission-->
		<form id="DETSampleForm" method="post" action="DETSample.jsp">
			<% try
				{ 
			%>
			<table>
				<tr>
					<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b><%=dataEntryTemplate.getName()%></b></td>
				</tr>
				<tr>
					<td><%=renderDataEntryTemplate(dataEntryTemplate)%></td>
				</tr>
				<tr>
					<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="btnCreateItem" value="Create Content Item" id="btnCreateItem" /></td>
				</tr>
			</table>
			<% } 
			   catch(Exception ex)
			   {
			      jspOut.println("<font color='#ff0000'>Exception: " + ex.getMessage() + "</font><br>");
			   } 
			%>
		</form>
	</body>
</HTML>