package jp.sourceforge.shovel.action.impl;

import javax.servlet.http.HttpServletRequest;

import jp.sourceforge.shovel.FormatType;
import jp.sourceforge.shovel.action.IFollowNotificationAction;
import jp.sourceforge.shovel.entity.IFriendship;
import jp.sourceforge.shovel.entity.IStatus;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.form.IFriendsForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;

public class FollowNotificationActionImpl implements IFollowNotificationAction {
    IFriendsForm actionForm_;
    HttpServletRequest request_;
    
    public String perform() throws Exception {
        FormatType formatType = actionForm_.getFormatType();
        long userId = actionForm_.getUserId();
        String foreignKey = actionForm_.getForeignKey();
        
        IShovelService shovelService = getShovelService();
        IFriendship friendship = null;
        if (foreignKey.matches("^[0-9]+$")) {
            foreignKey = null;
            friendship = shovelService.updateNotification(userId, true);
        } else {
            userId = 0;
            friendship = shovelService.updateNotification(foreignKey, true);
        }
        if (friendship == null) {
            //TODO
            throw new ApplicationException("");
        }
        
        String forward = null;
        switch (formatType) {
        case HTML:
            break;
        case JSON:
        case XML:
            IStatus status;
            if (userId > 0) {
                status = shovelService.getRecent(userId);
            } else {
                status = shovelService.getRecent(foreignKey);
            }
            if (status == null) {
                IDirectoryService directoryService = shovelService.getDirectoryService();
                IUser user = directoryService.getUser(foreignKey);
                shovelService.prepareForView(new IUser[] {user}, 1);
                request_.setAttribute("user", user);
            } else {
                shovelService.prepareForView(status);
                request_.setAttribute("status", status);
                request_.setAttribute("user", status.getSender());
            }
            forward = formatType.getId();
            break;
        default:
            throw new ApplicationException("");
        }
        return forward;
    }
    
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setFriendshipForm(IFriendsForm actionForm) {
        actionForm_ = actionForm;
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
}
