package jp.sourceforge.shovel.action.impl;

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

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

import org.seasar.framework.container.S2Container;

import jp.sourceforge.shovel.FormatType;
import jp.sourceforge.shovel.action.IDirectMessagesAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IDirectMessage;
import jp.sourceforge.shovel.entity.IFriendship;
import jp.sourceforge.shovel.entity.IListRefine;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.form.IDirectMessagesForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;

//TODO 削除されたユーザーを友だちから削除
public class DirectMessagesActionImpl implements IDirectMessagesAction {
    IDirectMessagesForm actionForm_;
    HttpServletRequest request_;
    S2Container container_;
    
    @Perform(CSRF=false)
    public String perform() throws Exception {
        FormatType formatType = actionForm_.getFormatType();
        
        IShovelService shovelService = getShovelService();
        IDirectoryService directoryService = shovelService.getDirectoryService();
        IUser user = directoryService.getLoginUser();
        
        int page = actionForm_.getPage();
        int limit = actionForm_.getCount();
        boolean sent = !actionForm_.isReceive();
        if (formatType.isHtml()) {
            IListRefine listRefine = (IListRefine)getSession().getAttribute(S_LIST_REFINE);
            if (listRefine == null || !(listRefine.getViewType().isInbox() || listRefine.getViewType().isSent())) {
                listRefine = (IListRefine)container_.getComponent(IListRefine.class);
                getSession().setAttribute(S_LIST_REFINE, listRefine);
            } else if (actionForm_.getMethodType().isPage()) {
                listRefine.setPage(actionForm_.getPage());
            }
            listRefine.setViewType(sent ? SENT: INBOX);
            
            if (!shovelService.isMobilePhone()) {
                page = listRefine.getPage();
            }
            limit = 0;
        }
        
        String foreignKey = actionForm_.getRecipient();
        long userId;
        if (foreignKey.matches("^[0-9]+$")) {
            userId = Long.valueOf(foreignKey);
        } else {
            userId = 0;
        }
        IUser recipient = null;
        if (userId > 0) {
            recipient = directoryService.getUser(userId);
        } else if (foreignKey != null && foreignKey.length() > 0){
            recipient = directoryService.getUser(foreignKey);
        }
        if (recipient != null) {
            if (recipient.getUserId() == user.getUserId()) {
                //TODO 自分自身には送信させない
                throw new ApplicationException("");
            }
            request_.setAttribute("recipient", recipient);
            request_.setAttribute("user", recipient);
            return shovelService.isMobilePhone() ? MOBILE : FULL;
        }
        
        IDirectMessage[] temp = shovelService.getDirectMessages(sent, page, limit);
        IDirectMessage[] directMessages = shovelService.prepareForView(temp, true);
        request_.setAttribute("directMessages", directMessages);
        
        String forward = null;
        switch (formatType) {
        case HTML:
            shovelService.prepareForView(user);
            request_.setAttribute("user", user);
            
            if (shovelService.isMobilePhone()) {
                request_.setAttribute("page", page);
                forward = MOBILE;
            } else {
                foreignKey = user.getForeignKey();
                IFriendship[] followers = shovelService.getFollowers(foreignKey, false, 0, 65535);
                followers = shovelService.prepareForView(followers, 0, false);
                request_.setAttribute("followers", followers);
                IFriendship[] friendships = shovelService.getFriends(foreignKey, 0, 100);
                request_.setAttribute("viewAllFriends", friendships.length > 100);
                friendships = shovelService.prepareForView(friendships, 100, true);
                request_.setAttribute("friendships", friendships);
                
                forward = actionForm_.isPartial() ? PARTIAL : FULL;
            }
            
            boolean nextPage = false;
            if (directMessages != null && directMessages.length > 0) {
                nextPage = temp.length > directMessages.length;
            }
            request_.setAttribute("nextPage", nextPage);
            break;
        case JSON:
        case XML:
            forward = formatType.getId();
            break;
        case ATOM:
        case RSS:
            shovelService.outputFeed(formatType, INBOX, user, directMessages);
            break;
        default:
            throw new ApplicationException("");
        }
        
        return forward;
    }
    
    public void setDirectMessagesForm(IDirectMessagesForm actionForm) {
        actionForm_ = actionForm;
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
    public void setContainer(S2Container container) {
        container_ = container;
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    HttpSession getSession() {
        return request_.getSession(true);
    }
}
