/* $Id: LoginAction.java,v 1.10 2005/08/26 04:45:06 ysahara Exp $
*
* Copyright (c)ARGO 21, Corporation. 2005.  All rights reserved.
 * 
 * This file is part of Nautica Workflow.
 * 
 *  Nautica Workflow 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 2 of the License, or
 *  (at your option) any later version.
 * 
 *  Nautica Workflow 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 Nautica Workflow; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *  
*/
package jp.co.argo21.nautica.workflow.sample.action;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;

import jp.co.argo21.nautica.workflow.sample.actionform.UserBean;
import jp.co.argo21.nautica.workflow.sample.util.ResourceManager;
import jp.co.argo21.nautica.workflow.sample.util.SingletonServices;
import jp.co.argo21.nautica.workflow.sample.util.Constants;
import jp.co.argo21.nautica.workflow.sample.util.Validator;
import jp.co.argo21.nautica.workflow.security.Organization;
import jp.co.argo21.nautica.workflow.security.User;
import jp.co.argo21.nautica.workflow.security.simple.OrganizationManagerRemote;
import jp.co.argo21.nautica.workflow.security.simple.UserManagerRemote;
import jp.co.argo21.nautica.workflow.soap.WorkflowServiceConnector;
import jp.co.argo21.nautica.workflow.wfmc.ConnectionFailedException;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * ログインボタン押下時の処理を行うアクションクラス。
 * 
 * @author  ruchida(Argo 21, Corp.)
 * @version $Revision: 1.10 $
 * @since   Nautica Workflow 0.9
 */
public class LoginAction extends Action {
    
    /**
	 * ログイン処理を行う。
     * 
	 * @param mapping アクションマッピング
	 * @param form アクションフォーム
	 * @param request リクエスト
	 * @param response レスポンス
	 * @return アクションフォワード
	 */
	public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response ) 
    {
        UserBean userBean = (UserBean)form;
        String userID = userBean.getUserID();
        String password = userBean.getPassword();
        List errMsgs = new ArrayList();
        ResourceManager rm = ResourceManager.getInstance();
        
        // 入力された値が空文字かどうか判定する。
        if (Validator.isEmpty(userID)) {
            errMsgs.add(rm.getValue("login.user") + rm.getValue("error.empty"));
        }
        if (Validator.isEmpty(password)) {
            errMsgs.add(rm.getValue("login.password") + rm.getValue("error.empty"));
        }
        
        // 空文字のものがある場合、ログイン画面に遷移し、エラーを表示する。
        if (errMsgs.size() != 0) {
            request.setAttribute("errorMsg", errMsgs.toArray());
            return mapping.findForward(Constants.ERROR);
        }
        
        try {
            // エンジンに接続
            WorkflowServiceConnector conn = SingletonServices.getInstance().getWfConnection();
            String sessionID = conn.connect(userID, password);

            // ユーザ取得
            UserManagerRemote userManager = SingletonServices.getInstance().getUserManager();
            User user = userManager.getUser(userBean.getUserID());
            userBean.setUser(user);
            userBean.setName(user.getName());
            
            // 組織取得
            OrganizationManagerRemote osm = SingletonServices.getInstance().getOrganizationManager();
            Organization[] org = osm.getOrganizationByUser(user);
            
            // ユーザに値を設定
            if (org.length != 0) {
                userBean.setOrganizationID(org[0].getID());
                userBean.setOrganizationName(org[0].getName());
            } else {
                errMsgs.add(rm.getValue("error.login"));
                request.setAttribute("errorMsg" , errMsgs.toArray());
                return mapping.findForward(Constants.ERROR);
            }
            userBean.setSessionID(sessionID);
            
            request.getSession().setAttribute("user", userBean);
            return mapping.findForward(Constants.SUCCESS);
            
        } catch (ServiceException e) {
            // セッション無効化
            request.getSession().invalidate();
            // エンジンへの接続に失敗
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (ConnectionFailedException e) {
            if (e.getFaultString().indexOf("E1011") != -1
                    || e.getFaultString().indexOf("E1013") != -1){
                // 認証に失敗
                errMsgs.add(rm.getValue("error.login"));
                request.setAttribute("errorMsg" , errMsgs.toArray());
                return mapping.findForward(Constants.ERROR);
            }
            // セッション無効化
            request.getSession().invalidate();
            // エンジンへの接続に失敗
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (RemoteException e) {
            // セッション無効化
            request.getSession().invalidate();
            // エンジンへの接続に失敗
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (NamingException e) {
            // セッション無効化
            request.getSession().invalidate();
            // エンジンへの接続に失敗（ユーザ管理・組織管理取得失敗）
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.FATAL_ERROR);
        } catch (Exception e) {
            // セッション無効化
            request.getSession().invalidate();
            // 予期せぬエラー
            request.setAttribute("errMsg", e.toString());
            request.setAttribute("err", e.getStackTrace());
            return mapping.findForward(Constants.UNEXPECTED_ERROR);
        }        
        
    }
}