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.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.seasar.framework.container.S2Container;

import jp.sourceforge.shovel.FormatType;
import jp.sourceforge.shovel.action.IFavoritesAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IFriendship;
import jp.sourceforge.shovel.entity.IListRefine;
import jp.sourceforge.shovel.entity.IStatus;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.form.IStatusesForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;

public class FavoritesActionImpl implements IFavoritesAction {
    IStatusesForm actionForm_;
    HttpServletRequest request_;
    HttpServletResponse response_;
    S2Container container_;
    
    @Perform(CSRF=false, login=false)
    public String perform() throws Exception {
        IShovelService shovelService = getShovelService();
        IDirectoryService directoryService = shovelService.getDirectoryService();
        String foreignKey = actionForm_.getForeignKey();
        IUser user;
        boolean home = true;
        if (foreignKey == null || foreignKey.length() <= 0) {
            user = directoryService.getLoginUser();
        } else {
            user = directoryService.getUser(foreignKey);
            home = false;
        }
        if (user == null) {
            throw new ApplicationException("");
        }
        
        FormatType formatType = actionForm_.getFormatType();
        
        boolean protect = false;
        if (!home && user.isProtect()) {
            IUser loginUser = directoryService.getLoginUser();
            protect = true;
            if (loginUser != null) {
                if (loginUser.getUserId() == user.getUserId()) {
                    protect = false;
                } else {
                    IFriendship[] friends = shovelService.getRequests(user.getUserId());
                    //アクセスが許可されるのは次のケース
                    for (IFriendship tmp : friends) {
                        if (tmp.getRemovedTime() > 0) {
                            continue;
                        }
                        if (tmp.getPassiveId() == user.getUserId()) {
                            //1. 明示的にアクセスを許可される
                            protect &= !tmp.isAccept();
                            request_.setAttribute("friend", tmp);
                        } else {
                            //2. プロテクトしている側からフォロー
                            protect &= false;
                            request_.setAttribute("follower", tmp);
                        }
                    }
                }
            }
        }
        
        IStatus[] temp = null;
        IStatus[] statuses = new IStatus[0];
        IListRefine listRefine = (IListRefine)getSession().getAttribute(S_LIST_REFINE);
        if (listRefine == null || !listRefine.getViewType().isFavorites()) {
            listRefine = (IListRefine)container_.getComponent(IListRefine.class);
            getSession().setAttribute(S_LIST_REFINE, listRefine);
        } else if (actionForm_.getMethodType().isPage()) {
            listRefine.setPage(actionForm_.getPage());
        }
        listRefine.setViewType(FAVORITES);
        
        if (!protect) {
            int page = actionForm_.getPage();
            int limit = actionForm_.getCount();
            if (formatType.isHtml()) {
                page = listRefine.getPage();
                limit = 0;
            }
        
            temp = shovelService.getFavorites(user.getForeignKey(), page, limit);
            statuses = shovelService.prepareForView(temp, limit, true);
        }
        request_.setAttribute("protect", protect);
        
        String forward = null;
        switch (formatType) {
        case HTML:
            shovelService.prepareForView(user);
            request_.setAttribute("user", user);
            IFriendship[] friendships = shovelService.getFriends(user.getForeignKey(), 0, 100);
            request_.setAttribute("viewAllFriends", friendships.length > 100);
            friendships = shovelService.prepareForView(friendships, 100, true);
            request_.setAttribute("friendships", friendships);
            
            if (!protect) {
                boolean nextPage = false;
                if (statuses != null) {
                    nextPage = temp.length > statuses.length;
                }
                request_.setAttribute("nextPage", nextPage);
            }
            forward = actionForm_.isPartial() ? PARTIAL : FULL;
            break;
        case JSON:
        case XML:
            forward = formatType.getId();
            break;
        case ATOM:
        case RSS:
            shovelService.outputFeed(formatType, FAVORITES, user, statuses);
            break;
        default:
            throw new ApplicationException("");
        }
        request_.setAttribute("statuses", statuses);
        
        return forward;
    }
    public void setStatusesForm(IStatusesForm 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;
    }
    public void setResponse(HttpServletResponse response) {
        response_ = response;
    }
    HttpSession getSession() {
        return request_.getSession(true);
    }
}
