/*
 * Created on Aug 13, 2008 (C) Copyright TANDBERG Television Ltd.
 */

package com.tandbergtv.watchpoint.pmm.web.util;

import javax.servlet.http.HttpServletRequest;

/**
 * Class that helps get the values to display in an HTML Form by examining the data in the servlet
 * request parameters.
 * 
 * @author Vijay Silva
 */
public final class HTMLFormBuilder {

	/* Internal Constructor */
	private HTMLFormBuilder() {
	}

	/**
	 * Method to get the value for a Form Field that displays a single value
	 * 
	 * @param fieldName The Form Field Name
	 * @param request The Servlet Request
	 * @return The value of the field or empty string if no value exists.
	 */
	public static String getValue(String fieldName, HttpServletRequest request) {
		return getValue(fieldName, request, 0);
	}

	/**
	 * Method to get the value for a Form Field that displays multiple values. Requires the 0-based
	 * index of the value to display.
	 * 
	 * @param fieldName The Form Field Name
	 * @param request The Servlet Request
	 * @param index The 0 based index to display
	 * @return The value of the field or empty string if no value exists.
	 */
	public static String getValue(String fieldName, HttpServletRequest request, int index) {
		String value = "";

		if (index < 0) {
			throw new IllegalArgumentException("The form field index cannot be less than 0.");
		}

		String[] values = request.getParameterValues(fieldName);
		if (values != null && index < values.length) {
			value = (values[index] != null) ? values[index] : "";
		}

		/* Need to escape quotes in the value since value is displayed in input field */
		return value.replaceAll("\"", "&quot;");
	}

	/**
	 * Check if the option value is one of the submitted values for a field
	 * 
	 * @param fieldName The Form Field Name
	 * @param request The Servlet Request
	 * @param option The value to test against
	 * @return true if option value is one of the submitted values for the form, false otherwise
	 */
	public static boolean isOptionSelected(String fieldName, HttpServletRequest request,
			String option) {
		boolean selected = false;

		String[] values = request.getParameterValues(fieldName);
		if (values != null) {
			for (String value : values) {
				if (option.equals(value)) {
					selected = true;
					break;
				}
			}
		}

		return selected;
	}
}
