package jp.sourceforge.shovel.action.impl;

import javax.servlet.http.HttpServletRequest;

import net.arnx.jsonic.JSON;

import org.seasar.framework.container.S2Container;


import jp.sourceforge.shovel.action.IPictureAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.entity.IServerFile;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.form.IPictureForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IServerFileService;
import jp.sourceforge.shovel.service.IShovelService;
import jp.sourceforge.shovel.util.ServerFileUtil;

public class PictureActionImpl implements IPictureAction {
    IPictureForm actionForm_;
    HttpServletRequest request_;
    S2Container container_;
    
    class JSONBean {
        IUser user_;
        IServerFile serverFile_;
        
        public JSONBean(IUser user) {
            user_ = user;
            serverFile_ = user_.getProfileImage();
        }
        public String getForeignKey() {
            return user_.getForeignKey();
        }
        public IServerFile getServerFile() {
            return serverFile_ == null ? null : serverFile_;
        }
    }
    
    @Perform(CSRF=true)
    public String perform() throws Exception {
        IShovelService shovelService = getShovelService();
        IDirectoryService directoryService = shovelService.getDirectoryService();
        IUser user = directoryService.getLoginUser();
        IServerFile serverFile = user.getProfileImage();
        IServerFileService serverFileService = shovelService.getServerFileService();
        if (serverFile.isExists()) {
            serverFileService.removeServerFile(serverFile);
        }
        serverFile = ServerFileUtil.toServerFile(actionForm_.getFile(), null, null);
        if (serverFile.isExists()) {
            serverFileService.createServerFile(serverFile, true, false);
        }
        user.setProfileImage(serverFile);
        directoryService.updateUser(user);
        shovelService.prepareForView(new IUser[] {user}, 1);
        
        String json = JSON.encode(new JSONBean(user));
        request_.setAttribute("content", "(" + json + ")");
        request_.setAttribute("callback", "window.parent.shovel.controller.onUpdatePicture(eval($('#content').html()));");
        return SUCCESS;
    }
    public void setPictureForm(IPictureForm actionForm) {
        actionForm_ = actionForm;
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setContainer(S2Container container) {
        container_ = container;
    }
}
