package jp.sourceforge.shovel.action.impl;

import static jp.sourceforge.shovel.CommonConst.*;
import static jp.sourceforge.shovel.SessionConst.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jp.sourceforge.shovel.action.ILoginAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.form.ILoginForm;
import jp.sourceforge.shovel.service.IShovelService;
import jp.sourceforge.shovel.util.HttpUtil;

public class LoginActionImpl implements ILoginAction {
    ILoginForm actionForm_;
    IShovelService shovelService_;
    HttpServletRequest request_;
    HttpServletResponse response_;
    
    @Perform(CSRF=false, login=false)
    public String perform() throws Exception {
        //フォーム認証はログイン情報をセッションに積む
        IUser user = shovelService_.getDirectoryService().login(actionForm_.getAccount(),
                actionForm_.getPassword(), false);
        String url;
        if (user == null) {
            //セッション経由でエラーを伝播
            //getSession().setAttribute(S_ERROR_CODE, "LOGIN00000");
            //getSession().setAttribute(S_ACTION_FORM, actionForm_);
            getSession().setAttribute("notification", "warning.loginFailure");
            url = "/";
        } else {
            if (!shovelService_.isMobilePhone()) {
                //クッキーにユーザ名書き出し
                Cookie cookie = new Cookie(LOGIN_COOKIE_NAME, actionForm_.getAccount());
                cookie.setPath("/");
                if (actionForm_.isSaveAccount()) {
                    //賞味期限は1週間
                    cookie.setMaxAge(60 * 60 * 24 * 7);
                } else {
                    //即削除
                    cookie.setMaxAge(0);
                }
                response_.addCookie(cookie);
            }
            //UrlRewriteFilterでつんでれ
            url = (String)getSession().getAttribute(S_LOGIN_REDIRECT_URL);
            if (url == null) {
                url = "/public_timeline";
            }
        }
        HttpUtil.sendRedirect(response_, url);
        return null;
    }
    public void setShovelService(IShovelService shovelService) {
        shovelService_ = shovelService;
    }
    public void setLoginForm(ILoginForm actionForm) {
        actionForm_ = actionForm;
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setResponse(HttpServletResponse response) {
        response_ = response;
    }
    HttpSession getSession() {
        return request_.getSession(true);
    }
}
