/*
 * Creado el 21-ene-04
 */
package es.ejie.frmk.presentacion.iu.taglib.base;

import javax.servlet.http.HttpServletRequest;

import es.ejie.frmk.control.arranque.Q70GestorArranqueConfiguracion;
import es.ejie.frmk.listeners.listasenlazadas.Q70ListasEnlazadasTag;
import es.ejie.frmk.listeners.validadorremoto.Q70ValidadorRemotoTag;
import es.ejie.frmk.presentacion.iu.taglib.html.table.Q70TableTag;

/**
 * @author UFRM002
 */
public class Q70JavascriptLib {

	/**
	 * Usado por el tag: Q70TableTag.java Descripcion: Si la tabla permite
	 * ordenacion o paginación, devuelve el codigo javascript necesario para que
	 * la tabla funcione en modo POST (en vez de en el modo por defecto GET). Si
	 * no permite estas dos cosas, devuelve "".
	 */
	public static String renderTableTagPOSTMethodCode(HttpServletRequest req, Q70TableTag tag) {
		// Obtener un nombre aleatorio para la capa que crea la clase javascript
		// FrmkLayer.
		StringBuffer buf = new StringBuffer(500);
		String frmkScriptsPath = Q70GestorArranqueConfiguracion.getGlobalProperty(Q70Constants.FRMK_STATIC_PATH_KEY)+ Q70GestorArranqueConfiguracion.getGlobalProperty(Q70Constants.FRMK_STATIC_ALIAS_KEY) + Q70Constants.FRMK_SCRIPTS_PATH;
		buf.append("\r\n");
		if (!tag.isInPageContext("FrmkBrowserSniffer.js")) {
			buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkBrowserSniffer.js\" type=\"text/javascript\"></script> \r\n");
			tag.putInPageContext("FrmkBrowserSniffer.js");
		}
		if (!tag.isInPageContext("FrmkLayer.js")) {
			buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkLayer.js\" type=\"text/javascript\"></script> \r\n");
			tag.putInPageContext("FrmkLayer.js");
		}
		if (!tag.isInPageContext("FrmkForm.js")) {
			buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkForm.js\" type=\"text/javascript\"></script> \r\n");
			tag.putInPageContext("FrmkForm.js");
		}
		if (!tag.isInPageContext("FrmkTableTag.js")) {
			buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkTableTag.js\" type=\"text/javascript\"></script> \r\n");
			tag.putInPageContext("FrmkTableTag.js");
		}			

		return (buf != null ? buf.toString() : "");
	}

	// ----------------------------------------------------------------------------------------------------------------
	// ----------------------------------------------------------------------------------------------------------------

	/**
	 * Usado por el tag: Q70ValidadorRemotoTag.java Descripcion: Compone el
	 * codigo html necesario para llamar al Gestor de Validaciones Remotas.
	 * @param (String) bridgeBaseUrl: url base (sin parametros) a la que llama
	 *        el bridge
	 * @param (Q70ValidadorRemotoTag) tag: objeto que tiene los datos de los
	 *        parametros a añadir a la url base
	 * @return (String): codigo html para llamar al Gestor de Validaciones
	 *         Remotas
	 */

	public static String renderValidadorRemotoHtmlCode(HttpServletRequest req, Q70ValidadorRemotoTag tag) {
		// Nombre del servlet encargado de hacer la validacion remota
		// private static final String VALIDATOR_SERVLET_NAME =
		// "/q70remoteValidatorServlet";
		String VALIDATOR_SERVLET_NAME = Q70GestorArranqueConfiguracion.getApplicationProperty("JavascriptLib", null, "ALIAS_VALIDADOR_REMOTO");
		String frmkScriptsPath = Q70GestorArranqueConfiguracion.getGlobalProperty(Q70Constants.FRMK_STATIC_PATH_KEY) + Q70GestorArranqueConfiguracion.getGlobalProperty(Q70Constants.FRMK_STATIC_ALIAS_KEY) + Q70Constants.FRMK_SCRIPTS_PATH;
		StringBuffer buf = new StringBuffer(1000);
		String bridgeName = tag.getBridgeName();

		if (Q70Constants.IFRAME_TECH.equalsIgnoreCase(tag.getTechnology())) {
			// código propio para la tecnología Iframe
			if (!tag.isInPageContext("FrmkBrowserSniffer.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkBrowserSniffer.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkBrowserSniffer.js");
			}
			if (!tag.isInPageContext("FrmkIframe.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkIframe.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkIframe.js");
			}
			if (!tag.isInPageContext("FrmkForm.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkForm.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkForm.js");
			}
			if (!tag.isInPageContext("FrmkBridge.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkBridge.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkBridge.js");
			}

			buf.append("<script language=\"JavaScript\" type=\"text/javascript\"> \r\n")
				.append("var ").append(bridgeName).append(" = new FrmkBridge(\"").append(bridgeName).append("\"); \r\n")
				.append("function ").append(tag.getJavascriptValidateFunc()).append("(){ \r\n")
				.append(" var u=\"").append(getBridgeBaseUrl(req, VALIDATOR_SERVLET_NAME)).append("?formName=").append((tag.getFormName().length() > 0 ? tag.getFormName() : ""))
				.append("&sourceTag=").append((tag.getSourceTag().length() > 0 ? tag.getSourceTag() : ""))
				.append("&sourceTagValue=");
			if (null != tag.getSourceTag() && 0 < tag.getSourceTag().length()) {
				buf.append("\"+").append(getHtmlFieldValue("", tag.getFormName(), tag.getSourceTag())).append("+\"");
			}
			buf.append("&targetTag=").append((tag.getTargetTag().length() > 0 ? tag.getTargetTag() : ""))
			.append("&targetTagValue=");
			if (null != tag.getTargetTag() && 0 < tag.getTargetTag().length()) {
				buf.append("\"+").append(getHtmlFieldValue("", tag.getFormName(), tag.getTargetTag())).append("+\"");
			}
			buf.append("&retFunc=").append((tag.getJavascriptReturnFunc() != null ? tag.getJavascriptReturnFunc() : ""))
				.append("&table=").append((tag.getTable() != null ? tag.getTable() : ""))
				.append("&subjectColumn=").append((tag.getSubjectColumn().length() > 0 ? tag.getSubjectColumn() : ""))
				.append("&predicateColumn=").append((tag.getPredicateColumn().length() > 0 ? tag.getPredicateColumn() : ""))
				.append("&predicateColumnNumeric=").append(tag.getPredicateColumnNumeric())
				.append("&extraPredicate=").append((tag.getExtraPredicate().length() > 0 ? tag.getExtraPredicate() : ""))
				.append("&technology=").append((tag.getTechnology().length() > 0 ? tag.getTechnology() : "")).append("\"; \r\n ")

					.append(bridgeName);
			if (tag.getSubmitMethod().toUpperCase().equals("POST")) {
				buf.append(".doSubmit(u);  \r\n");
			} else {
				buf.append(".doRedirect(u);  \r\n");
			}

			buf.append("} \r\n").append("</script> \r\n");
		} else if (Q70Constants.AJAX_TECH.equalsIgnoreCase(tag.getTechnology())) {
			// código propio para la tecnología Ajax
			if (!tag.isInPageContext("FrmkAjax.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkAjax.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkAjax.js");
			}

			buf.append("<script language=\"JavaScript\" type=\"text/javascript\"> \r\n")
				.append("function ").append(tag.getJavascriptValidateFunc()).append("(){ \r\n")
				.append(" var u=\"").append(getBridgeBaseUrl(req, VALIDATOR_SERVLET_NAME)).append("\"; \r\n ")
				.append(" var method=\"").append(tag.getSubmitMethod()).append("\"; \r\n ")
				.append(" var parametros = \"formName=").append((tag.getFormName().length() > 0 ? tag.getFormName() : ""))
				.append("&sourceTag=").append((tag.getSourceTag().length() > 0 ? tag.getSourceTag() : ""))
				.append("&sourceTagValue=");
			if (null != tag.getSourceTag() && 0 < tag.getSourceTag().length()) {
				buf.append("\"+").append(getHtmlFieldValue("", tag.getFormName(), tag.getSourceTag())).append("+\"");
			}
			buf.append("&targetTag=").append((tag.getTargetTag().length() > 0 ? tag.getTargetTag() : ""))
			.append("&targetTagValue=");
			if (null != tag.getTargetTag() && 0 < tag.getTargetTag().length()) {
				buf.append("\"+").append(getHtmlFieldValue("", tag.getFormName(), tag.getTargetTag())).append("+\"");
			}
			buf.append("&retFunc=").append((tag.getJavascriptReturnFunc() != null ? tag.getJavascriptReturnFunc() : ""))
				.append("&table=").append((tag.getTable() != null ? tag.getTable() : ""))
				.append("&subjectColumn=").append((tag.getSubjectColumn().length() > 0 ? tag.getSubjectColumn() : ""))
				.append("&predicateColumn=").append((tag.getPredicateColumn().length() > 0 ? tag.getPredicateColumn() : ""))
				.append("&predicateColumnNumeric=").append(tag.getPredicateColumnNumeric())
				.append("&extraPredicate=").append((tag.getExtraPredicate().length() > 0 ? tag.getExtraPredicate() : ""))
				.append("&technology=").append((tag.getTechnology().length() > 0 ? tag.getTechnology() : "")).append("\"; \r\n ")
				.append("fncPeticionAjax (u, parametros, method);  \r\n");

			buf.append("} \r\n").append("</script> \r\n");
		}

		return (buf != null ? buf.toString() : "");
	}

	// ----------------------------------------------------------------------------------------------------------------
	// ----------------------------------------------------------------------------------------------------------------

	/**
	 * Compone el codigo html necesario para llamar al listener de Listas
	 * Enlazadas en modo GET.
	 * @param (String) submitMethod: modo de submit. Valores posibles: GET |
	 *        POST
	 * @param (String) bridgeName: nombre del objeto bridge
	 * @param (String) bridgeBaseUrl: url base (sin parametros) a la que llama
	 *        el bridge
	 * @param (int) bridgeCounter: contador de objetos bridge por pagina
	 * @param (Q70ListasEnlazadasTag) tag: objeto que tiene los datos de los
	 *        parametros a añadir a la url base
	 * @return (String): codigo html para llamar al listener de Listas Enlazadas
	 */
	public static String renderListasEnlazadasHtmlCode(HttpServletRequest req, Q70ListasEnlazadasTag tag) {
		// Nombre del servlet encargado de las Listas Enlazadas
		// private static final String LISTS_SERVLET_NAME =
		// "/q70joinedListsServlet";
		String LISTS_SERVLET_NAME = Q70GestorArranqueConfiguracion.getApplicationProperty("JavascriptLib", null, "ALIAS_LISTAS_ENLAZADAS");
		String frmkScriptsPath = Q70GestorArranqueConfiguracion.getGlobalProperty(Q70Constants.FRMK_STATIC_PATH_KEY)
				+ Q70GestorArranqueConfiguracion.getGlobalProperty(Q70Constants.FRMK_STATIC_ALIAS_KEY) + Q70Constants.FRMK_SCRIPTS_PATH;
		StringBuffer buf = new StringBuffer(1000);
		String bridgeName = tag.getBridgeName();

		if (Q70Constants.IFRAME_TECH.equalsIgnoreCase(tag.getTechnology())) {
			if (!tag.isInPageContext("FrmkBrowserSniffer.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkBrowserSniffer.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkBrowserSniffer.js");
			}
			if (!tag.isInPageContext("FrmkIframe.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkIframe.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkIframe.js");
			}
			if (!tag.isInPageContext("FrmkForm.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkForm.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkForm.js");
			}
			if (!tag.isInPageContext("FrmkBridge.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkBridge.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkBridge.js");
			}
			if (!tag.isInPageContext("FrmkScripts.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkScripts.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkScripts.js");
			}
			buf.append("<script language=\"JavaScript\"> \r\n")
				.append("var ").append(bridgeName).append(" = new FrmkBridge(\"").append(bridgeName).append("\"); \r\n")
				.append("function ").append(tag.getJavascriptCallerFunc()).append("(){ \r\n")
				.append(" var u=\"").append(getBridgeBaseUrl(req, LISTS_SERVLET_NAME))
				.append("?formName=").append((tag.getFormName().length() > 0 ? tag.getFormName() : ""))
				.append("&sourceTag=").append((tag.getSourceTag().length() > 0 ? tag.getSourceTag() : ""))
				.append("&sourceTagValue=");
			if (null != tag.getSourceTag() && 0 < tag.getSourceTag().length()) {
				buf.append("\"+").append(getHtmlFieldValue("LIST", tag.getFormName(), tag.getSourceTag())).append("+\"");
			}
			buf.append("&targetTag=").append((tag.getTargetTag().length() > 0 ? tag.getTargetTag() : ""));
			/*
			 * .append("&targetTagValue="); if (null!=tag.getTargetTag() && 0<tag.getTargetTag().length()) {
			 * buf.append("\"+") .append(
			 * getHtmlFieldValue("LIST",tag.getFormName(),tag.getTargetTag()) )
			 * .append("+\""); }
			 */
			buf.append("&retFunc=").append((tag.getJavascriptReturnFunc() != null ? tag.getJavascriptReturnFunc() : ""))
				.append("&table=").append((tag.getTable() != null ? tag.getTable() : ""))
				.append("&labelColumn=").append((tag.getLabelColumn().length() > 0 ? tag.getLabelColumn() : ""))
				.append("&valueColumn=").append((tag.getValueColumn().length() > 0 ? tag.getValueColumn() : ""))
				.append("&predicateColumn=").append((tag.getPredicateColumn().length() > 0 ? tag.getPredicateColumn() : ""))
				.append("&predicateColumnNumeric=").append(tag.getPredicateColumnNumeric())
				.append("&extraPredicate=").append((tag.getExtraPredicate().length() > 0 ? tag.getExtraPredicate() : ""))
				.append("&technology=").append((tag.getTechnology().length() > 0 ? tag.getTechnology() : "")).append("\"; \r\n ")
				.append(bridgeName);
			if (tag.getSubmitMethod().toUpperCase().equals("POST")) {
				buf.append(".doSubmit(u);  \r\n");
			} else {
				buf.append(".doRedirect(u);  \r\n");
			}

			buf.append("} \r\n").append("</script> \r\n");
		} else if (Q70Constants.AJAX_TECH.equalsIgnoreCase(tag.getTechnology())) {
			// código propio para la tecnología Ajax
			if (!tag.isInPageContext("FrmkAjax.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkAjax.js\" type=\"text/javascript\"></script> \r\n");
				tag.putInPageContext("FrmkAjax.js");
			}
			if (!tag.isInPageContext("FrmkScripts.js")) {
				buf.append("<script language=\"JavaScript\" src=\"").append(frmkScriptsPath).append("/FrmkScripts.js\"></script> \r\n");
				tag.putInPageContext("FrmkScripts.js");
			}
			buf.append("<script language=\"JavaScript\" type=\"text/javascript\"> \r\n")
				.append("function ").append(tag.getJavascriptCallerFunc()).append("(){ \r\n")
				.append(" var u=\"").append(getBridgeBaseUrl(req, LISTS_SERVLET_NAME)).append("\"; \r\n ")
				.append(" var method=\"").append(tag.getSubmitMethod()).append("\"; \r\n ")
				.append(" var parametros = \"formName=").append((tag.getFormName().length() > 0 ? tag.getFormName() : ""))
				.append("&sourceTag=").append((tag.getSourceTag().length() > 0 ? tag.getSourceTag() : ""))
				.append("&sourceTagValue=");
			if (null != tag.getSourceTag() && 0 < tag.getSourceTag().length()) {
				buf.append("\"+").append(getHtmlFieldValue("LIST", tag.getFormName(), tag.getSourceTag())).append("+\"");
			}
			buf.append("&targetTag=").append((tag.getTargetTag().length() > 0 ? tag.getTargetTag() : ""));
			/*
			 * .append("&targetTagValue="); if (null!=tag.getTargetTag() && 0<tag.getTargetTag().length()) {
			 * buf.append("\"+") .append(
			 * getHtmlFieldValue("LIST",tag.getFormName(),tag.getTargetTag()) )
			 * .append("+\""); }
			 */
			buf.append("&retFunc=").append((tag.getJavascriptReturnFunc() != null ? tag.getJavascriptReturnFunc() : ""))
				.append("&table=").append((tag.getTable() != null ? tag.getTable() : ""))
				.append("&labelColumn=").append((tag.getLabelColumn().length() > 0 ? tag.getLabelColumn() : ""))
				.append("&valueColumn=").append((tag.getValueColumn().length() > 0 ? tag.getValueColumn() : ""))
				.append("&predicateColumn=").append((tag.getPredicateColumn().length() > 0 ? tag.getPredicateColumn() : ""))
				.append("&predicateColumnNumeric=").append(tag.getPredicateColumnNumeric())
				.append("&extraPredicate=").append((tag.getExtraPredicate().length() > 0 ? tag.getExtraPredicate() : ""))
				.append("&technology=").append((tag.getTechnology().length() > 0 ? tag.getTechnology() : "")).append("\"; \r\n ")
				.append("fncPeticionAjax (u, parametros, method);  \r\n").append("} \r\n")
				.append("</script> \r\n");
		}

		return (buf != null ? buf.toString() : "");
	}

	// -------------------------------------------------------------------------------------------------
	// Private Methods
	/**
	 * Devuelve la forma javascript de obtener el valor de un campo de un
	 * formulario HTML.
	 * @param (String) formName: nombre del formulario donde esta el campo
	 * @param (String) fieldName: nombre del campo
	 */
	private static String getHtmlFieldValue(String type, String formName, String fieldName) {

		StringBuffer sb = null;
		if ((null != formName && 0 < formName.length()) && (null != fieldName && 0 < fieldName.length())) {
			sb = new StringBuffer(formName.length() + fieldName.length() + 20);

			// Devolver una forma de acceso al valor del campo segun su tipo.
			if (type.equals("LIST")) {
				// Es una lista desplegable
				sb.append("document.").append(formName).append(".").append(fieldName).append(".options[").append("document.").append(formName).append(".").append(fieldName).append(
						".selectedIndex].value");
			} else {
				sb.append("document.").append(formName).append(".").append(fieldName).append(".value");
			}
		}
		return (null != sb ? sb.toString() : "");
	}

	/**
	 * Compone la base de la url con la que se comunica el objeto bridge.
	 * @param (HttpServletRequest) req: request asociada al tag a pintar
	 * @param (String) urlComponente: url del componente (servlet) al que llama
	 *        el objeto bridge
	 * @return (String): url de base del objeto bridge
	 */
	private static String getBridgeBaseUrl(HttpServletRequest req, String urlComponente) {

		StringBuffer bridgeBaseUrl = new StringBuffer(256);

		bridgeBaseUrl.append(req.getContextPath()).append(urlComponente);

		return bridgeBaseUrl.toString();
	}
}
