/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.core.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

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

import nuts.core.lang.Strings;


@SuppressWarnings("serial")
public class PageRedirectServlet extends HttpServlet {
	/**
	 * welcomeFile
	 */
	private String welcomeFile;

	/**
	 * redirectURL
	 */
	private String redirectURL;
	
	/**
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		welcomeFile = servletConfig.getInitParameter("welcomeFile");
		redirectURL = servletConfig.getInitParameter("redirectURL");
	}

	private String getRedirectURL(String page) {
		String url = redirectURL;
		
		page = getServletContext().getRealPath(page);
		File file = new File(page);
		if (file.exists()) {
			BufferedReader br;
			try {
				br = new BufferedReader(new FileReader(file));
				String ln = br.readLine();
				if (Strings.isNotEmpty(ln)) {
					url = ln;
				}
			}
			catch (Exception ex) {
			}
		}
		
		return url;
	}
	
	/**
	 *
	 */
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		String page = request.getRequestURI();
		if (page.endsWith("/")) {
			page += welcomeFile;
		}
		
		String url = this.getRedirectURL(page);
		
		HttpServletUtils.sendRedirect(response, url);
	}

	/**
	 * @see javax.servlet.GenericServlet#destroy()
	 */
	@Override
	public void destroy() {
	}
}
