package org.ow2.jonas.webapp.jonasadmin.service.depmonitor;

import java.io.IOException;

import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;

public class ApplyDepmonitorConfigurationAction extends JonasBaseAction {

    @Override
    public ActionForward executeAction(final ActionMapping mapping, final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException, ServletException {
        // Form used
        DepMonitorServiceForm oForm = (DepMonitorServiceForm) form;
        try {
            // Object name used
            String domainName = m_WhereAreYou.getCurrentDomainName();
            String jonasServerName = m_WhereAreYou.getCurrentJonasServerName();
            ObjectName on = JonasObjectName.deployableMonitorService(domainName);
            boolean dvpMode = false;
            if (oForm.isDevelopmentMode()) {
                dvpMode = true;
            }

            Boolean value = new Boolean(dvpMode);
            JonasManagementRepr.setAttribute(on, "development", value, jonasServerName);

            // Configure period
            int monitorInterval = oForm.getMonitorInterval();
            setIntegerAttribute(on, "monitorPeriod", monitorInterval);
            
            if (oForm.getAction().equals("save")) {
                JonasManagementRepr.invoke(on, "saveConfig", null, null, jonasServerName);
            }
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(request, m_Errors);
            return (mapping.findForward("Global Error"));
        }

        // Forward to action
        return (mapping.findForward("Depmonitor Service"));
    }

}
