package jp.sourceforge.shovel.action.impl;

import javax.servlet.http.HttpServletRequest;

import org.seasar.framework.container.S2Container;

import jp.sourceforge.shovel.FormatType;
import jp.sourceforge.shovel.action.ICreateDirectMessageAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IDirectMessage;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.form.IDirectMessageForm;
import jp.sourceforge.shovel.service.IShovelService;

public class CreateDirectMessageActionImpl implements ICreateDirectMessageAction {
    IDirectMessageForm actionForm_;
    HttpServletRequest request_;
    S2Container container_;
    
    @Perform(CSRF=true)
    public String perform() throws Exception {
        FormatType formatType = actionForm_.getFormatType();
        
        String foreignKey = actionForm_.getForeignKey();
        long userId;
        if (foreignKey == null || foreignKey.length() <= 0) {
            throw new ApplicationException("");
        } else if (foreignKey.matches("^[0-9]+$")) {
            userId = Long.valueOf(foreignKey);
        } else {
            userId = 0;
        }
        
        IShovelService shovelService = getShovelService();
        String text = actionForm_.getText();
        String source = actionForm_.getSource();
        IDirectMessage directMessage;
        if (userId > 0) {
            directMessage = shovelService.createDirectMessage(userId, text, source);
        } else {
            directMessage = shovelService.createDirectMessage(foreignKey, text, source);
        }
        
        String forward = null;
        switch (formatType) {
        case HTML:
            if (shovelService.isMobilePhone()) {
                request_.setAttribute("post", "sendDirectMessage");
                forward = MOBILE;
            }
            break;
        case JSON:
        case XML:
            shovelService.prepareForView(new IDirectMessage[] {directMessage}, false);
            request_.setAttribute("directMessage", directMessage);
            
            forward = formatType.getId();
            break;
        default:
            throw new ApplicationException("");
        }
        return forward;
    }
    
    public void setDirectMessageForm(IDirectMessageForm 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;
    }
}
