package jp.sourceforge.shovel.action.impl;

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

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

import jp.sourceforge.shovel.SortOrderType;
import jp.sourceforge.shovel.action.IDestroyAccountsAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IListRefine;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.form.IAccountsForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;

public class DestroyAccountsActionImpl implements IDestroyAccountsAction {
    IAccountsForm actionForm_;
    HttpServletRequest request_;
    
    @Perform(CSRF=true, administrator=true)
    public String perform() throws Exception {
        IShovelService shovelService = getShovelService();
        IDirectoryService directoryService = shovelService.getDirectoryService();
        long[] userIds = actionForm_.getUserIds();
        if (userIds != null && userIds.length > 0) {
            directoryService.removeUsers(userIds);
        } else {
            directoryService.removeUser(actionForm_.getUserId());
        }
        IListRefine listRefine = (IListRefine)getSession().getAttribute(S_LIST_REFINE);
        SortOrderType sortOrderType = listRefine.getSortOrderType();
        //0頁目に戻す
        IUser[] users = directoryService.getUsers(USER_ID, sortOrderType, 0);
        if (users != null && users.length > 0) {
            IUser[] tmp = shovelService.prepareForView(users, 0);
            request_.setAttribute("nextPage", tmp.length > users.length);
            users = tmp;
        }
        request_.setAttribute("users", users);
        
        return SUCCESS;
    }
    public void setAccountsForm(IAccountsForm actionForm) {
        actionForm_ = actionForm;
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    HttpSession getSession() {
        return request_.getSession(true);
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
}
