package jp.sourceforge.shovel.action.impl;

import java.util.HashMap;
import java.util.Map;

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

import org.seasar.framework.container.S2Container;

import jp.sourceforge.shovel.action.IShowUserAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IStatus;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.form.IUserForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;

/**
 * TODO Emailでの検索はまだ。。
 */
public class ShowUserActionImpl implements IShowUserAction {
    IUserForm actionForm_;
    javax.servlet.ServletContext context_;
    HttpServletRequest request_;
    HttpServletResponse response_;
    S2Container container_;
    
    @Perform(CSRF=false)
    public String perform() throws Exception {
        IShovelService shovelService = getShovelService();
        IDirectoryService directoryService = shovelService.getDirectoryService();
        
        String foreignKey = actionForm_.getForeignKey();
        long userId = actionForm_.getUserId();
        IUser user;
        if (foreignKey == null || foreignKey.length() <= 0) {
            user = directoryService.getLoginUser();
        } else if (foreignKey.matches("^[0-9]+$")) {
            user = directoryService.getUser(userId);
        } else {
            user = directoryService.getUser(foreignKey);
        }
        shovelService.prepareForView(new IUser[] {user}, 1);
        request_.setAttribute("user", user);
        
        IStatus status = null;
        if (userId > 0) {
            status = shovelService.getRecent(userId);
        } else {
            status = shovelService.getRecent(foreignKey);
        }
        Map<String, IStatus> statusMap = new HashMap<String, IStatus>();
        statusMap.put(String.valueOf(user.getUserId()), status);
        request_.setAttribute("statuses", statusMap);
        
        return actionForm_.getFormat();
    }
    public void setContainer(S2Container container) {
        container_ = container;
    }
    public void setContext(ServletContext context) {
        context_ = context;
    }
    public void setUserForm(IUserForm actionForm) {
        actionForm_ = actionForm;
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setResponse(HttpServletResponse response) {
        response_ = response;
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
}
