package cn.myapps.runtime.dynaform.form;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

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

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.util.StringUtil;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.form.service.FormDesignTimeService;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.form.ejb.Options;
import cn.myapps.runtime.dynaform.form.ejb.SuggestField;
import cn.myapps.runtime.dynaform.form.ejb.ValidateMessage;
import cn.myapps.runtime.macro.runner.IRunner;
import cn.myapps.runtime.macro.runner.JavaScriptFactory;
import cn.myapps.util.DbTypeUtil;
import cn.myapps.common.util.cache.MemoryCacheUtil;

public class SuggestFieldQueryServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = -5717733496173672993L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doQuery(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doQuery(req, resp);
	}

	private void doQuery(HttpServletRequest request,
						 HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			ParamsTable params = ParamsTable.convertHTTP(request);
			WebUser user = AuthTimeServiceManager.getWebUser(request);
			String formFieldId = params.getParameterAsString("_formFieldId");
			//TODO hotfix 兼容网格视图
			String formid = params.getParameterAsString("_formid") == null ? params.getParameterAsString("FormID") : params.getParameterAsString("_formid");
			String docid = params.getParameterAsString("content.id") == null ? params.getParameterAsString("DocumentID") : params.getParameterAsString("content.id");
			String parentId = params.getParameterAsString("parentid");
			if (docid != null && docid.equals(parentId)) {
				parentId = null;
				params.removeParameter("parentid");
			}

			FormDesignTimeService formService = DesignTimeServiceManager.formDesignTimeService();
			Form form = (Form) formService.doView(formid);
			SuggestField field = (SuggestField) form.findField(formFieldId);
			Document doc = null;

			if (field.getOptionsScript() != null
					&& field.getOptionsScript().trim().length() > 0) {
				if (!StringUtil.isBlank(docid)) {
					doc = (Document) MemoryCacheUtil.getFromPrivateSpace(docid,
							user);
					if (doc != null) {
						doc.setId(docid);
					}
				} else if (!StringUtil.isBlank(parentId)) {
					doc = (Document) MemoryCacheUtil.getFromPrivateSpace(parentId,user);
				}
				doc = form.createDocument(doc, params, user);

				params.setParameter("_keyword",
						params.getParameterAsString("__keyword"));

				IRunner runner = JavaScriptFactory.getInstance(
						user.getSessionid(),
						params.getParameterAsString("application"));
				runner.initBSFManager(doc, params, user,
						new ArrayList<ValidateMessage>());
				Options options = field.getOptions(runner);

				out.write(options.toJSON4SuggestField());
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			out.close();
			try {
				PersistenceUtils.closeSessionAndConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private String getQByDBType(String q, String applicationId)
			throws Exception {
		String dbType = DbTypeUtil.getDBType(applicationId);
		if (dbType.equals(DbTypeUtil.DBTYPE_MSSQL)) {
			q = q.replaceAll("%", "[%]");
			q = q.replaceAll("_", "[_]");
		} else {
			q = q.replaceAll("%", "\\\\%");
			q = q.replaceAll("_", "\\\\_");
		}
		return q;
	}
}
