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.IUserTimelineAction;
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 UserTimelineActionImpl implements IUserTimelineAction {
    IStatusesForm actionForm_;
    HttpServletRequest request_;
    S2Container container_;
    
    @Perform(CSRF=false, login=false)
    public String perform() throws Exception {
        IShovelService shovelService = getShovelService();
        IDirectoryService directoryService = shovelService.getDirectoryService();
        String foreignKey = actionForm_.getForeignKey();
        long userId = actionForm_.getUserId();
        IUser user = null;
        if (foreignKey == null || foreignKey.length() <= 0) {
            user = directoryService.getLoginUser();
        } else if (foreignKey.matches("^[0-9]+$")) {
            user = directoryService.getUser(userId);
        } else {
            user = directoryService.getUser(foreignKey);
        }
        if (user == null) {
            //TODO
            throw new ApplicationException("");
        }
        
        FormatType formatType = actionForm_.getFormatType();
        
        boolean protect = false;
        if (user.isProtect()) {
            protect = true;
            IUser login = directoryService.getLoginUser();
            if (login != null) {
                if (login.getUserId() == user.getUserId()) {
                    protect = false;
                } else {
                    IFriendship[] friends = shovelService.getRequests(user.getUserId());
                    //アクセスが許可されるのは次のケース
                    for (IFriendship friend : friends) {
                        if (friend.getRemovedTime() > 0) {
                            continue;
                        }
                        if (friend.getPassiveId() == user.getUserId()) {
                            //1. 明示的にアクセスを許可される
                            protect &= !friend.isAccept();
                            request_.setAttribute("friend", friend);
                        } else {
                            //2. プロテクトしている側からフォロー
                            if (login.isProtect()) {
                                //3. ログインユーザがプロテクトしているなら明示的なアクセスの許可が必要
                                protect &= !friend.isAccept();
                            } else {
                                protect &= false;
                            }
                            request_.setAttribute("follower", friend);
                        }
                    }
                }
            }
        }
        
        int page = actionForm_.getPage();
        String since = actionForm_.getSince();
        int limit = actionForm_.getCount();
        int correctedOffset = 0;
        int correctedLimit = 0;
        IStatus[] statuses = new IStatus[0];
        IListRefine listRefine = (IListRefine)getSession().getAttribute(S_LIST_REFINE);
        if (listRefine == null || !listRefine.getViewType().isUserTimeline()) {
            listRefine = (IListRefine)container_.getComponent(IListRefine.class);
            getSession().setAttribute(S_LIST_REFINE, listRefine);
        } else if (actionForm_.getMethodType().isPage()) {
            listRefine.setPage(actionForm_.getPage());
        }
        listRefine.setViewType(USER_TIMELINE);
        
        if (!protect) {
            if (formatType.isHtml()) {
                if (!shovelService.isMobilePhone()) {
                    page = listRefine.getPage();
                }
                
                limit = 0;
                if (page > 0) {
                    correctedOffset = 1;
                }
                correctedLimit = 2;
                
                statuses = shovelService.getStatuses(user.getForeignKey(), false, page, limit, correctedOffset, correctedLimit);
            } else {
                if (since == null || since.length() <= 0) {
                    since = request_.getHeader("If-Modified-Since");
                }
                if (since == null || since.length() <= 0) {
                    statuses = shovelService.getStatuses(user.getForeignKey(), false, page, limit, 0, 0);
                } else {
                    statuses = shovelService.getStatuses(user.getForeignKey(), false, since, limit);
                }
            }
        }
        request_.setAttribute("protect", protect);
        shovelService.prepareForView(statuses, limit, false);
        
        String forward = null;
        switch (formatType) {
        case HTML:
            shovelService.prepareForView(user);
            request_.setAttribute("user", user);
            if (!protect) {
                IFriendship[] friends = shovelService.getRequests(user.getUserId());
                for (IFriendship friend : friends) {
                    if (friend.getRemovedTime() > 0) {
                        continue;
                    }
                    if (friend.getPassiveId() == user.getUserId()) {
                        request_.setAttribute("friend", friend);
                    } else {
                        request_.setAttribute("follower", friend);
                    }
                }
                
                IStatus[] temp = statuses;
                int offset = 0;
                if (shovelService.isMobilePhone()) {
                    offset = page > 0 ? 0 : 1;
                }
                statuses = shovelService.truncate(temp, offset, limit);
                boolean nextPage = false;
                if (statuses != null && statuses.length + offset < temp.length) {
                    nextPage = temp.length > statuses.length;
                }
                request_.setAttribute("nextPage", nextPage);
            }
            if (shovelService.isMobilePhone()) {
                shovelService.prepareForView(user.getRecentlyStatus());
                IFriendship friendship = shovelService.getFriend(user.getForeignKey());
                request_.setAttribute("friendship", friendship);
                request_.setAttribute("page", page);
                forward = FORWARD_MOBILE;
            } else {
                IFriendship[] friendships = shovelService.getFriends(user.getForeignKey(), 0, 100);
                request_.setAttribute("viewAllFriends", friendships.length > 100);
                friendships = shovelService.prepareForView(friendships, 100, true);
                request_.setAttribute("friendships", friendships);
                forward = actionForm_.isPartial() ? FORWARD_AJAX : FORWARD_HTML;
            }
            break;
        case XML:
        case JSON:
            forward = formatType.getId();
            break;
        case ATOM:
        case RSS:
            shovelService.outputFeed(formatType, USER_TIMELINE, 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;
    }
    HttpSession getSession() {
        return request_.getSession(true);
    }
}
