package jp.sourceforge.shovel.action.impl;

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

import net.arnx.jsonic.JSON;

import jp.sourceforge.shovel.action.IDeviceAction;
import jp.sourceforge.shovel.device.IDelayExecutor;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.exception.ApplicationException;
import jp.sourceforge.shovel.form.IDeviceForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;
import jp.sourceforge.shovel.thread.DelayExecutorQueue;

public class DeviceActionImpl implements IDeviceAction {
    IDeviceForm actionForm_;
    HttpServletRequest request_;
    HttpServletResponse response_;
    DelayExecutorQueue queue_;
    
    class JSONBean {
        IUser user_;
        IDelayExecutor executor_;
        
        public JSONBean(IUser user, IDelayExecutor executor) {
            user_ = user;
            executor_ = executor;
        }
        public String getReleaseKey() throws ApplicationException {
            return user_.getReleaseKey();
        }
        public String getAddress() {
            if (executor_ == null) {
                return null;
            }
            return executor_.getAddress();
        }
    }
    
    public String perform() throws Exception {
        IUser user = getDirectoryService().getLoginUser();
        IDelayExecutor executor = null;
        
        switch (actionForm_.getPhase()) {
        default:
        case 0:  //デバイスの種類とアドレスの入力
            String deviceType = actionForm_.getDeviceType();
            String address = actionForm_.getAddress();
            getShovelService().createDevice(deviceType, address);
            executor = queue_.getDelayExecutor(deviceType);
            break;
        case 1:  //やり直し
            getShovelService().resetDevice();
            break;
        case 2:  //使用する機能
            getShovelService().updateDevice(actionForm_.getAvailabilityType());
            break;
        }
        
        String json = JSON.encode(new JSONBean(user, executor));
        response_.getOutputStream().write(json.getBytes("UTF-8"));
        
        return null;
    }
    public void setDeviceForm(IDeviceForm actionForm) {
        actionForm_ = actionForm;
    }
    public IDirectoryService getDirectoryService() {
        return getShovelService().getDirectoryService();
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setResponse(HttpServletResponse response) {
        response_ = response;
    }
    public void setDelayExecutorQueue(DelayExecutorQueue queue) {
        queue_ = queue;
    }
}
