/******************************************************************************
 * The contents of this file are subject to the   Compiere License  Version 1.1
 * ("License"); You may not use this file except in compliance with the License
 * You may obtain a copy of the License at http://www.compiere.org/license.html
 * Software distributed under the License is distributed on an  "AS IS"  basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial
 * Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke
 * are Copyright (C) 1999-2005 Jorg Janke.
 * All parts are Copyright (C) 1999-2005 ComPiere, Inc.  All Rights Reserved.
 * Contributor(s): ______________________________________.
 *****************************************************************************/
package com.ampiere.web.servlet;

import java.io.IOException;
import java.util.logging.Level;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ecs.AlignType;
import org.apache.ecs.xhtml.div;
import org.apache.ecs.xhtml.form;
import org.apache.ecs.xhtml.input;
import org.apache.ecs.xhtml.table;
import org.apache.ecs.xhtml.td;
import org.apache.ecs.xhtml.tr;
import org.compiere.model.GridField;
import org.compiere.framework.Query;
import org.compiere.util.CLogger;
import org.compiere.util.Msg;
import org.compiere.util.WebDoc;
import org.compiere.util.WebEnv;
import org.compiere.util.WebSessionCtx;
import org.compiere.util.WebUtil;

import com.ampiere.util.AmpiereUtil;

/**
 *	HTML Find UI.
 *  @author Siqine
 *  @version  $Id: WFind.java,v 1.1 2010/01/13 11:51:46 clmg Exp $
 */
public class WFind extends HttpServlet {
    /**  */
	private static final long serialVersionUID = 6617424544044122702L;
	/**	Logger. */
    private CLogger log = CLogger.getCLogger(getClass());

	/**
	 * Initialize global variables.
     * @param config config
     * @throws ServletException ServletException
	 */
	public final void init(final ServletConfig config)
		throws ServletException	{
		super.init(config);
		if (!WebEnv.initWeb(config)) {
			throw new ServletException("WProcess.init");
        }
	}   //  init

	/**
	 * Process the HTTP Get request Initial Call.
     * @param request request
     * @param response response
     * @throws ServletException ServletException
     * @throws IOException IOException
	 */
	public final void doGet(final HttpServletRequest request, final HttpServletResponse response)
		throws ServletException, IOException {

        //  Get Session attributes
	  	WebSessionCtx wsc = WebSessionCtx.get(request);
		if (wsc == null) {
			WebUtil.createTimeoutPage(request, response, this, null);
			return;
		}
		
		WebDoc doc = createFindPage(request);

		if (doc == null) {
			doc = WebDoc.createWindow("Error");
		}

		// Add body onUnload event, close all popup window when unload 
		doc.getBody().setOnUnload("closeMyChildren();");

		//
		WebUtil.createResponse(request, response, this, null, doc, false);
	}   //  doGet


	/**
	 * Process the HTTP Post request. Get Parameters and Process.
     * @param request request
     * @param response response
     * @throws ServletException ServletException
     * @throws IOException IOException
	 */
	public final void doPost(final HttpServletRequest request, final HttpServletResponse response)
		throws ServletException, IOException {

        //  Get Session attributes
	  	WebSessionCtx wsc = WebSessionCtx.get(request);
		WWindowStatus ws = WWindowStatus.get(request);
		if (wsc == null) {
			WebUtil.createTimeoutPage(request, response, this, null);
			return;
		}

		//	Create Query String
//		MQuery query = new MQuery(ws.curTab.getTableName());
		Query query = new Query(ws.curTab.getTableName());
		// m_query.addRestriction( ws.curTab.getWhereExtended() );

		GridField[] findFields = GridField.createFields(
                ws.ctx, ws.curTab.getWindowNo(), 0, ws.curTab.getAD_Tab_ID(), 0);
		
		for (int i = 0; i < findFields.length; i++) {

			GridField field = findFields[i];
			String columnName = field.getColumnName();

			if (columnName.equals("Value")) {
				String value = WebUtil.getParameter(request, columnName).toUpperCase();
				if (!value.equals("") && !value.equals("%")) {
					if (!value.endsWith("%")) {
						value += "%";
                    }
//                    query.addRestriction("UPPER(Value)", MQuery.LIKE, value);
                    query.addRestriction("UPPER(Value)", Query.LIKE, value);
				}
			} else if (columnName.equals("Name")) {
				String value = WebUtil.getParameter(request, columnName).toUpperCase();
				if (!value.equals("") && !value.equals("%")) {
					if (!value.endsWith("%")) {
						value += "%";
                    }
//                    query.addRestriction("UPPER(Name)", MQuery.LIKE, value);
                    query.addRestriction("UPPER(Name)", Query.LIKE, value);
				}
			} else if (columnName.equals("DocumentNo")) {
				String value = WebUtil.getParameter(request, columnName).toUpperCase();
				if (!value.equals("") && !value.equals("%")) {
					if (!value.endsWith("%")) {
						value += "%";
                    }
//                    query.addRestriction("UPPER(DocumentNo)", MQuery.LIKE, value);
                    query.addRestriction("UPPER(DocumentNo)", Query.LIKE, value);
				}
			} else if (columnName.equals("Description")) {
				String value = WebUtil.getParameter(request, columnName).toUpperCase();
				if (!value.equals("") && !value.equals("%")) {
					if (!value.endsWith("%")) {
						value += "%";
                    }
//                    query.addRestriction("UPPER(Description)", MQuery.LIKE, value);
                    query.addRestriction("UPPER(Description)", Query.LIKE, value);
				}
			// Jirimuto added for selection column - start 2009/03/29
			//} else if (field.isSelectionColumn() &&  {
			} else if (field.isSelectionColumn() ) {
				boolean notSQL = columnName.equals(field.getColumnSQL(false)) ;
				String value = WebUtil.getParameter(request, columnName);
				if (notSQL && value != null && value.toString().length() > 0)
				{
					log.fine(columnName + "=" + value);
					if (value.toString().indexOf("%") != -1)
						query.addRestriction(columnName, Query.LIKE, value);
					else
						query.addRestriction(columnName, Query.EQUAL, value, columnName, value);
				}
			}				
			// Jirimuto added for selection column - end 2009/03/29
		}

		// Jirimuto added for selection column - end 2009/03/29
		if (query != null && query.isActive())
			ws.curTab.setQuery(query);
		else 
			ws.curTab.setQuery(null);
//		ws.curTab.query(ws.curTab.isOnlyCurrentRows(), 0);
		ws.curTab.query(0);
		
		WebDoc doc = WebDoc.createWindow(ws.curTab.getTableName());
		doc.getBody().addElement(ws.curTab.getQuery().getWhereClause());
		StringBuffer sb = new StringBuffer();
		sb.append("<script language='javascript'>");
		sb.append("   opener.document.WForm.PCommand.value='Refresh';");
		sb.append("   opener.document.WForm.submit();");
		sb.append("   window.close();");
		sb.append("</script>");
		doc.getBody().addElement(sb.toString());

		WebUtil.createResponse(request, response, this, null, doc, false);
	}   //  doPost

	/**
	 * 	Create Find Page.
	 *	@param request request
	 *	@return Page
	 */
	private WebDoc createFindPage(final HttpServletRequest request) {
	  	WebSessionCtx wsc = WebSessionCtx.get(request);
		WWindowStatus ws = WWindowStatus.get(request);

		WebDoc doc = WebDoc.createWindow(ws.curTab.getTableName());
		
		// For date picker
		AmpiereUtil.addDatePicker(doc.getHead(), wsc);

		form myForm = new form(request.getRequestURI());
		myForm.setID("WFind");
		
		table myTable = new table();
		myTable.setAlign("CENTER");
		
		div divBody = (div)new div().setID("body"); //clmg 2009/02/24
		divBody.addElement(myTable);//clmg 2009/02/24

//		GridField[] findFields = GridField.createFields(
//                ws.ctx, ws.curTab.getWindowNo(), 0, ws.curTab.getAD_Tab_ID());
		GridField[] findFields = GridField.createFields(
                ws.ctx, ws.curTab.getWindowNo(), 0, ws.curTab.getAD_Tab_ID(), 0);
		
		for (int i = 0; i < findFields.length; i++) {
			tr myTr = new tr();

			GridField field = findFields[i];
			String columnName = field.getColumnName();

			if (columnName.equals("Value")) {
				addField(wsc, myTr, field, field.getDefault(), false, false);
				myTable.addElement(myTr);
			} else if (columnName.equals("Name")) {
				addField(wsc, myTr, field, field.getDefault(), false, false);
				myTable.addElement(myTr);
			} else if (columnName.equals("DocumentNo")) {
				addField(wsc, myTr, field, field.getDefault(), false, false);
				myTable.addElement(myTr);
			} else if (columnName.equals("Description")) {
				addField(wsc, myTr, field, field.getDefault(), false, false);
				myTable.addElement(myTr);
			// Jirimuto added for selection column - start 2009/03/29
			} else if (field.isSelectionColumn()) {
				addField(wsc, myTr, field, field.getDefault(), false, false);
				myTable.addElement(myTr);
			}
			// Jirimuto added for selection column - end 2009/03/29
		}

		tr myTr = new tr(new td(WebDoc.NBSP).setColSpan(2));
		myTable.addElement(myTr);

		//	Submit
//		myTable.addElement(new tr()
//			   .addElement(new td(null, AlignType.LEFT, AlignType.MIDDLE, false,
//                       new input(input.TYPE_RESET, "Reset", Msg.translate(wsc.ctx, "Reset"))))
//			   .addElement(new td(null, AlignType.CENTER, AlignType.MIDDLE, false, null))
//			   .addElement(new td(null, AlignType.RIGHT, AlignType.MIDDLE, false,
//                       new input(input.TYPE_SUBMIT, "Submit", Msg.translate(wsc.ctx, "Start")))));
		
		//clmg 2009/02/24
		td buttonTd = new td().addElement(new input(input.TYPE_RESET, "Reset", Msg.translate(wsc.ctx, "Reset")));
		buttonTd.addElement(new input(input.TYPE_SUBMIT, "Submit", Msg.translate(wsc.ctx, "Start")));
		buttonTd.setColSpan(2);
		buttonTd.setAlign(AlignType.CENTER);
		myTable.addElement(new tr()
		   .addElement(buttonTd));
		//--

//		myForm.addElement(myTable); //clmg 2009/02/24
		myForm.addElement(divBody); //clmg 2009/02/24
		doc.getBody().addElement(myForm);

		return doc;
	}	//	createFindPage
	
	/**
	 *	Add Field to Line.
	 *  @param wsc session context
	 *  @param line format element
	 *  @param field field
     *  @param oData original data
     *  @param readOnly readOnly
	 *  @param hasDependents has Callout function(s)
	 */
	private void addField(
			final WebSessionCtx wsc,
			final tr line,
			final GridField field,
			final Object oData,
			final boolean hasDependents,
			final boolean readOnly
			) {
		String columnName = field.getColumnName();
		//  Any Error?
        Object data = oData;
		boolean error = field.isErrorValue();
		if (error) {
            log.log(Level.SEVERE, oData.toString());
            data = field.getErrorValue();
        }
		int dt = field.getDisplayType();
		boolean hasCallout = field.getCallout().length() > 0;

		/**
		 *  HTML Label Element
		 *      ID = ID_columnName
		 *
		 *  HTML Input Elements
		 *      NAME = columnName
		 *      ID = ID_columnName
		 */
		
		int display_length = field.getDisplayLength();
//		if( display_length > 40 ){
//			display_length = 48;
//		} else {
//			display_length = 20;			
//		}
		
		if( display_length > 500 ){
			display_length = 550;
		} else {
			display_length = 200;			
		}
				
		WebField wField = new WebField(
                field.getWindowNo(),
                wsc,
                columnName,
                field.getHeader(),
                field.getDescription(),
                dt,
                field.getFieldLength(),
                display_length,
                field.isLongField(),
                readOnly,
                field.isMandatory(false),
                error,
                hasDependents,
                hasCallout,
                field.getAD_Process_ID(),
                field.isEncryptedField());

		line.addElement(wField.getLabel());
		line.addElement(wField.getField(field.getLookup(), data, field.getAD_Column_ID()));
	}	//	addField

}   //  WFind
