/*  OpenOlap viewer
 *  パッケージ名：openolap.viewer.controller
 *  ファイル：LoginCommand.java
 *  説明：
 *
 *  作成日: 2004/01/30
 */
package openolap.viewer.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import openolap.viewer.User;
import openolap.viewer.common.CommonSettings;
import openolap.viewer.dao.DAOFactory;
import openolap.viewer.dao.UserDAO;

/**
 *  クラス：LoginCommand
 *  説明：
 */
public class LoginCommand implements Command {

	private RequestHelper requestHelper = null;

	// ********** メソッド **********

	public String execute(RequestHelper helper, CommonSettings commonSettings)
		throws ServletException, IOException {

		String nextPage = null;

		this.requestHelper = helper;
		HttpServletRequest request = this.requestHelper.getRequest();
		HttpSession session = this.requestHelper.getRequest().getSession();

		// ユーザチェック
		String userName = request.getParameter("user");
		String password = request.getParameter("password");

		if ( (userName == null) && (password == null) ) {
			return "/jsp/flow/login.jsp";
		}

		Connection conn = null;
		DAOFactory daoFactory = DAOFactory.getDAOFactory();
		conn = daoFactory.getConnection();
	
		UserDAO userDAO =  daoFactory.getUserDAO(conn);
		User user = null;
		try {
			user = userDAO.getUser(userName, password);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}

		if ( user == null ) {
			nextPage = "/login.jsp";
			request.setAttribute("loginResult", "failed");
		} else {

			// UserオブジェクトをSessionに登録
			request.getSession().setAttribute("user", user);
			nextPage = "/spread/redirectTo.jsp";
			request.setAttribute("redirectTo", "/OpenOLAP.html");
		}

		return nextPage;
	}

}
