package jp.sourceforge.shovel.action.impl;

import static jp.sourceforge.shovel.CommonConst.*;

import java.util.Properties;
import java.util.TimeZone;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.seasar.framework.container.S2Container;


import jp.sourceforge.shovel.AccountConfigType;
import jp.sourceforge.shovel.action.IAccountAction;
import jp.sourceforge.shovel.annotation.Perform;
import jp.sourceforge.shovel.device.IDelayExecutor;
import jp.sourceforge.shovel.entity.IDevice;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.form.IAccountForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;
import jp.sourceforge.shovel.thread.DelayExecutorQueue;
import jp.sourceforge.shovel.util.HttpUtil;
import jp.sourceforge.shovel.util.ShovelUtil;

public class AccountActionImpl implements IAccountAction {
    IAccountForm actionForm_;
    ServletContext context_;
    HttpServletRequest request_;
    HttpServletResponse response_;
    S2Container container_;
    DelayExecutorQueue queue_;
    
    @Perform(CSRF=false, login=false)
    public String perform() throws Exception {
        IShovelService shovelService = getShovelService();
        IDirectoryService directoryService = shovelService.getDirectoryService();
        IUser user = directoryService.getLoginUser();
        AccountConfigType configType = actionForm_.getConfigType();
        
        if (configType.isDevice() && !(Boolean)context_.getAttribute("device")) {
            //基本情報にリダイレクト
            HttpUtil.sendRedirect(response_, "/account/settings");
            return null;
        } else if (!(configType.isProfileImage() || configType.isResendPassword() || configType.isResetPassword()) && user == null) {
            //プロフィール画像、パスワード再送、パスワードリセット以外はログインが必要
            HttpUtil.sendRedirect(response_, "/");
            return null;
        }
        
        switch (configType) {
        case SETTINGS:
            String[] tzIDs = TimeZone.getAvailableIDs();
            TimeZone[] tzs = new TimeZone[tzIDs.length];
            int i = 0;
            for (String tzID : tzIDs) {
                tzs[i++] = TimeZone.getTimeZone(tzID);
            }
            request_.setAttribute("tzs", tzs);
            break;
        case DEVICE:
            IDevice device = user.getDevice();
            if (!device.getDeviceType().isUnknown()) {
                IDelayExecutor executor = queue_.getDelayExecutor(device.getType());
                if (executor == null) {
                    //設定が消えた？何にせよおかしいから、設定をやり直し
                    getShovelService().resetDevice();
                } else {
                    request_.setAttribute("address", executor.getAddress());
                    request_.setAttribute("releaseKey", user.getReleaseKey());
                }
            }
            break;
        case PICTURE:
            Properties props = (Properties)container_.getComponent(COMMON_PROPERTIES);
            String maxSize = props.getProperty("upload.maxSize");
            request_.setAttribute("maxSize", Integer.parseInt(maxSize));
            break;
        case PROFILE_IMAGE:
            user = directoryService.getUser(actionForm_.getForeignKey());
            break;
        case DESIGN:
            //背景画像がない場合、Tileはtrue
            long backgroundImageId = user.getBackgroundImageId();
            if (backgroundImageId <= 0) {
                user.setTile(true);
            }
            break;
        case RESET_PASSWORD:
            user = directoryService.getUser(actionForm_.getEmail(), true);
            String token = ShovelUtil.generateToken(actionForm_.getEmail() + ":" + user.getPassword());
            if (token.compareTo(actionForm_.getToken()) != 0) {
                throw new ApplicationException("");
            }
            request_.setAttribute("email", actionForm_.getEmail());
            request_.setAttribute("token", actionForm_.getToken());
        case RESEND_PASSWORD:
        default:
            break;
        }
        shovelService.prepareForView(user);
        
        request_.setAttribute("domain", request_.getServerName());
        request_.setAttribute("port", request_.getServerPort());
        request_.setAttribute("config", configType);
        request_.setAttribute("user", user);
        
        return actionForm_.isPartial() ? configType.getForward() : FORWARD_ACCOUNT;
    }
    public void setContainer(S2Container container) {
        container_ = container;
    }
    public void setContext(ServletContext context) {
        context_ = context;
    }
    public void setAccountForm(IAccountForm actionForm) {
        actionForm_ = actionForm;
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setResponse(HttpServletResponse response) {
        response_ = response;
    }
    public void setDelayExecutorQueue(DelayExecutorQueue queue) {
        queue_ = queue;
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
}
