/*
 * 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.iframe;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
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.convert.ConvertUtils;
import woolpack.ee.EEContext;
import woolpack.ee.ServletInputStreamFactory;
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.idnode.IdNodeUtils;
import woolpack.utils.Utils;
import woolpack.xml.XmlTransformerContext;
import woolpack.xml.XmlTransformerUtils;
import woolpack.xml.XmlUtils;

/**
 * IFRAME を TABLE に変換するサンプル Web アプリケーションです。
 * @author nakamura
 *
 */
public class IFrameServlet 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 IFrameServlet() {
		super();
		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(IdNodeUtils.insertIFrame("common_parent", "target", FnUtils.seq(Utils.<Fn<? super EEContext, Void, ? extends Exception>>
						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(HtmlUtils.removeExtension("IFRAME", "src"))
				), FnUtils.<String>echo()))
		);
	}

	@Override public void init(final ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
		toNode.setFn(FnUtils.join(
				ConvertUtils.convertRegExp(Pattern.compile("^(.*)$"), "/html/sample/iframe/$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());

		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();
		}
	}
}
