/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.samples.transaction;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.regex.Pattern;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

import woolpack.action.ActionDefMaker;
import woolpack.action.ActionInvoker;
import woolpack.action.ForwardDef;
import woolpack.bool.BoolUtils;
import woolpack.convert.ConvertUtils;
import woolpack.ee.ActionBuilder;
import woolpack.ee.EEContext;
import woolpack.ee.EEUtils;
import woolpack.ee.HttpSessionMap;
import woolpack.ee.ServletInputStreamFactory;
import woolpack.el.PathEL;
import woolpack.factory.FactoryUtils;
import woolpack.fn.Delegator;
import woolpack.fn.Fn;
import woolpack.fn.FnUtils;
import woolpack.html.HtmlUtils;
import woolpack.id.IdUtils;
import woolpack.utils.Utils;
import woolpack.web.WebUtils;
import woolpack.xml.XmlTransformerContext;
import woolpack.xml.XmlTransformerUtils;
import woolpack.xml.XmlUtils;

/**
 * 画面遷移の順序を検証するサンプル Web アプリケーションです。
 * @author nakamura
 *
 */
public class TransactionServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public final transient Delegator<String, Node, Exception> toNode;
	public final transient Fn<EEContext, Void, Exception> fn;
	
	public TransactionServlet() throws Exception {
		super();
		
		final ActionBuilder actionBuilder = new ActionBuilder(
				new ActionInvoker(
						FnUtils.switching(new ActionDefMaker()
						.putForward("0")
						.putForward("1")
						.putForward("2").get()),
						new ForwardDef("simple_error", EEUtils.LOCAL_EL, FnUtils.fix(true))),
				Arrays.asList("name", "id"));

		toNode = new Delegator<String, Node, Exception>(null);

		fn = FnUtils.seq(Utils.<Fn<? super EEContext, Void, ? extends Exception>>
				list(IdUtils.<Void, RuntimeException>convertId(ConvertUtils.convertRegExp(Pattern.compile("^.*/([^/]+)$"), "$1")))
				.list(WebUtils.<EEContext, Void, Exception>checkTransactionToken(
						"transactionToken",
						FnUtils.join(IdUtils.GET_ID, BoolUtils.contains(Arrays.asList("1", "2"))),
						actionBuilder.getActionExpression(),
						IdUtils.<Void, RuntimeException>convertId(
								FnUtils.fix("simple_errorTransaction"))))
				.list(XmlUtils.<EEContext, Exception>setNode(FnUtils.join(IdUtils.GET_ID, toNode)))
				.list(HtmlUtils.NORMALIZE_CASE)
				.list(HtmlUtils.removeExtension("A", "href"))
				.list(HtmlUtils.removeExtension("FORM", "action"))
				.list(actionBuilder.getAutoUpdateExpression())
				.list(HtmlUtils.appendParameterAll(
						FnUtils.fix("transactionToken"),
						FnUtils.join(
								FactoryUtils.doEL(new PathEL("session.transactionToken")),
								ConvertUtils.TO_STRING), "UTF-8"))
		);
	}


	@Override public void init(final ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
		toNode.setFn(FnUtils.join(
				ConvertUtils.convertRegExp(Pattern.compile("^(.*)$"), "/html/sample/transaction/$1.html"),
				XmlUtils.nodeFactory(
						FactoryUtils.inputStreamReaderFactory(new ServletInputStreamFactory<IOException>(
						servletConfig.getServletContext()), "UTF-8"),
						XmlTransformerUtils.TRANSFORMER)));
	}

	@Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		final EEContext context = new EEContext();
		context.setId(request.getRequestURI());
		context.setInput(WebUtils.convert(request.getParameterMap()));
		context.setSession(Utils.concurrentMap(new HttpSessionMap(request.getSession()), request.getSession()));

		try {
			fn.exec(context);
		} catch (final Exception e) {
			throw new ServletException(e);
		}
		
		final Writer w = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
		try {
			final XmlTransformerContext tc = new XmlTransformerContext();
			tc.setSource(new DOMSource(context.getNode()));
			tc.setResult(new StreamResult(w));
			XmlTransformerUtils.TRANSFORMER.exec(tc);
		} catch (final TransformerException e) {
			throw new ServletException(e);
		} finally {
			w.close();
		}
	}
}
