//===========================================================================
// package
//===========================================================================
package jp.gr.java_conf.bugslife.action;

//===========================================================================
// import
//===========================================================================
import java.io.IOException;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.logging.*;
import org.apache.struts.action.*;
import org.apache.struts.util.*;
import org.apache.commons.beanutils.*;

import jp.gr.java_conf.bugslife.form.*;
import jp.gr.java_conf.bugslife.selections.*;
import jp.gr.java_conf.bugslife.user.*;
/**
 *<PRE>
 * 
 * LogonActionクラス
 *
 *</PRE>
 * @version	0.0
 * @author	鰐川 正寛
 */
public final class LogonAction extends BaseAction 
{
//===========================================================================
// attributes
//===========================================================================
	/**
	 * Log
	 */
	private Log log = LogFactory.getLog(this.getClass().getName());
//===========================================================================
// methods
//===========================================================================
	/**
	 * exevute
	 *
	 * @param mapping The ActionMapping used to select this instance
	 * @param actionForm The optional ActionForm bean for this request (if any)
	 * @param request The HTTP request we are processing
	 * @param response The HTTP response we are creating
	 *
	 * @exception Exception if business logic throws an exception
	 */
	public ActionForward doAction(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
				throws Exception {
	
		// Extract attributes we will need
		Locale locale = getLocale(request);
		MessageResources messages = getResources(request);
		
		ActionForward forward = null;
		
		//formの取得
		LogonForm myForm = (LogonForm)form;
		//sessioの取得
		
		String action = myForm.getAction();
		//debug
		log.debug("action = " + action);
		log.debug("bno = " + myForm.getBno());
		
		//初期表示
		if ((action == null) || (action.equals("show"))) {
			
			forward = mapping.findForward("init");
			
		//ログオン
		} else {
			//チェック
			ActionErrors errors = myForm.validate(mapping, request);
			if (!errors.empty()) {
				 saveErrors(request, errors);
				return (new ActionForward(mapping.getInput()));
			}
			String username = myForm.getUserName();
			String password = myForm.getPassword();
			
			UserInfo userInfo = UserInfo.findUid(username);
			
			/*-------------------------------
			//debug
			log.debug("userInfo get " + userInfo);
			-------------------------------*/
			//アカウントはあった？
			if (userInfo == null) {
				errors.add("username", new ActionError("error.username.invalid"));
				saveErrors(request, errors);
				return (new ActionForward(mapping.getInput()));
			}
			//ログイン可能か？
			if (!userInfo.checkEnableLogin()) {
				errors.add("username", new ActionError("error.user.notlogin"));
				saveErrors(request, errors);
				return (new ActionForward(mapping.getInput()));
			}
			//パスワードが正しいか？
			if (! password.equals(userInfo.getPassword())) {
				errors.add("password", new ActionError("error.password.unmatch"));
				saveErrors(request, errors);
				return (new ActionForward(mapping.getInput()));
			}
			
			//-------------------------
			//初回ログイン時の処理
			//------------------------
			HttpSession session = request.getSession(false);
			//既にセッションがあるか？
			if (session != null) {
				//そのセッションは破棄する
				session.invalidate();
			}
			session = request.getSession(true);		//

			
			
			//ディスパッチリストが空であれば、自分にディスパッチ出来るように追加する。
			
		    Collection dispatchList = DispatchList.getEnableDispatchList(userInfo.getUno());
		    //ディスパッチリストが１件もなく
		    if (dispatchList == null) {	
		        //該当のレコードが存在しない場合
		        if (!DispatchList.isExist(userInfo.getUno(), userInfo.getUno())) {
			        DispatchList dl = new DispatchList();
			        dl.setUno(userInfo.getUno());
			        dl.setDispatchUno(userInfo.getUno());
			        dl.insert(userInfo.getUno());
		        }
		    }
			
			//session.setAttribute("UserInfo", userInfo);
		    
		    //ログオンユーザをセッションにセット
		    SelectionSet.setLogonUser(session, userInfo);
		    //ディスパッチ先をセッションにセット
		    SelectionSet.setDispatchList(session, userInfo);
		    
		    
			//各種区分リストの設定
		    //本来なら初期化時に行うべきだが、ここでは、誰かがログインしたタイミングで
		    //初期化を行っている
			SelectionSet.setAll(session.getServletContext(), userInfo, false);
			

			//画面遷移
			//メールからのログオンの場合、全画面表示へ行く
			int bno = myForm.getBno();
			//bnoなし（通常のログオン）
			if (bno == 0) {
				forward = mapping.findForward("success");
			//bnoあり（メールからのログオン）
			} else {
				forward = new ActionForward("/showAll.do?action=show&bno=" + bno);
			}
			
		}
		// Forward control to the specified success URI
		return forward;
	}
}
