package com.collective.celos.servlet;

import java.util.List;

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

import com.collective.celos.Scheduler;
import com.collective.celos.SchedulerConfiguration;
import com.collective.celos.SlotState;
import com.collective.celos.Workflow;
import com.collective.celos.WorkflowID;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Returns information about the slot states of a single workflow as JSON.
 * 
 * GET /workflow?id=workflow-1
 * ==>
 * {
 *   "slots": {
 *     "2013-12-07T13:00:00.000Z": { "status": "RUNNING", "externalID": "237982137-371832798321-W", retryCount: 5 },
 *     "2013-12-07T14:00:00.000Z": { "status": "READY", "externalID": null, retryCount: 0 },
 *     ...
 *   }
 * }
 * 
 * If the "time" parameter is supplied, information is returned about 
 * slot states up to that time.
 */
@SuppressWarnings("serial")
public class JSONWorkflowServlet extends AbstractJSONServlet {

    private static final String ID_PARAM = "id";

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
        String id = req.getParameter(ID_PARAM);
        if (id == null) {
            throw new IllegalArgumentException(ID_PARAM + " parameter missing.");
        }
        try {
            Scheduler scheduler = new SchedulerConfiguration().makeDefaultScheduler();
            Workflow wf = scheduler.getWorkflowConfiguration().findWorkflow(new WorkflowID(id));
            if (wf == null) {
                throw new IllegalArgumentException("Workflow not found: " + id);
            }
            List<SlotState> slotStates = scheduler.getSlotStates(wf, getRequestTime(req));
            ObjectNode object = createJSONObject(slotStates);
            writer.writeValue(res.getOutputStream(), object);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    ObjectNode createJSONObject(List<SlotState> slotStates) {
        ObjectNode node = mapper.createObjectNode();
        for (SlotState state : slotStates) {
            node.put(state.getScheduledTime().toString(), state.toJSONNode());
        }
        return node;
    }

}

@@ -1595,43 +1595,56 @@
     
-throw new IllegalArgumentException(
+res.sendError(HttpServletResponse.SC_NOT_FOUND, 
 %22Wor
@@ -1674,33 +1674,42 @@
 );%0A            %7D
-%0A
+ else %7B%0A  
             List
@@ -1704,16 +1704,18 @@
         
+  
 List%3CSlo
@@ -1781,24 +1781,28 @@
 Time(req));%0A
+    
             
@@ -1863,16 +1863,20 @@
         
+    
 writer.w
@@ -1917,16 +1917,30 @@
 bject);%0A
+            %7D%0A
         

Send 404 error from JSONWorkflowServlet if workflow ID not found.