package jp.sourceforge.shovel.action.impl;

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

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

import org.seasar.framework.container.S2Container;

import jp.sourceforge.shovel.action.IResetPasswordAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.form.IAccountForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;
import jp.sourceforge.shovel.util.HttpUtil;
import jp.sourceforge.shovel.util.ShovelUtil;

public class ResetPasswordActionImpl implements IResetPasswordAction {
    IAccountForm actionForm_;
    HttpServletRequest request_;
    HttpServletResponse response_;
    S2Container container_;
    
    @Perform(CSRF=false, login=false)
    public String perform() throws Exception {
        IDirectoryService directoryService = getShovelService().getDirectoryService();
        IUser user = directoryService.getUser(actionForm_.getEmail(), true);
        String token = ShovelUtil.generateToken(actionForm_.getEmail() + ":" + user.getPassword());
        if (token.compareTo(actionForm_.getToken()) != 0) {
            throw new ApplicationException("");
        }
        
        directoryService.updatePassword(user, actionForm_.getPassword());
        user = directoryService.login(user.getForeignKey(), actionForm_.getPassword(), false);
        if (user == null) {
            throw new ApplicationException("");
        }
        getSession().setAttribute(S_NOTIFICATION, "notify.resetPassword");
        HttpUtil.sendRedirect(response_, "/");
        
        return null;
    }
    public void setContainer(S2Container container) {
        container_ = container;
    }
    public void setAccountForm(IAccountForm actionForm) {
        actionForm_ = actionForm;
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setResponse(HttpServletResponse response) {
        response_ = response;
    }
    public HttpSession getSession() {
        return request_.getSession();
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
}
