package com.capgemini.reports.r22;

import com.capgemini.reports.auto.AbstractAutoLaunchServlet;
import com.capgemini.reports.definition.r22report.ExecutionR22;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.capgemini.reports.execution.actions.DoNothingAction;
import com.capgemini.reports.execution.actions.IPostExecutionStep;
import com.capgemini.reports.execution.actions.IPreExecutionStep;
import com.capgemini.reports.execution.strategies.AutomaticExecutionStrategy;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * A Servlet which listens to calls from a workflow.
 */
@WebServlet("/autoR22")
public class R22AutoServlet extends AbstractAutoLaunchServlet<ExecutionR22> {

    private static final long serialVersionUID = -8586399099581830304L;

    private static final String URL_PARAMETER_PART_ID = "itemID";
    private static final String URL_PARAMETER_PART_REV = "revID";

    // Intercept the request: The WKF sends the Part UID, the the report is expecting partID & partRev.
    // A Forward is required to add arguments
    @Override
    protected ExecutionR22 processFunctionalParams(final HttpServletRequest aRequest) throws InsufficientParametersException {
        // Parse part ID
        String partID = aRequest.getParameter(URL_PARAMETER_PART_ID);
        if (partID == null || partID.isEmpty()) {
            throw new InsufficientParametersException("No part ID was provided in URL");
        }

        // Parse part REV
        String revID = aRequest.getParameter(URL_PARAMETER_PART_REV);
        if (revID == null || revID.isEmpty()) {
            throw new InsufficientParametersException("No part Revision was provided in URL");
        }

        // Make the report
        ExecutionR22 exec = new SubmitServletR22().prepareReport(partID, revID, aRequest);
        exec.isWkf();
        return exec;
    }

    @Override
    protected void setupSchedulingStrategy(String relaunchURL, ExecutionR22 report) {
        IPreExecutionStep specializedPreAction = new DoNothingAction();
        IPostExecutionStep specializedPostAction = report.makeAttachPdfToPartAction();
        report.setExecutionStrategy(new AutomaticExecutionStrategy(relaunchURL, specializedPreAction, specializedPostAction));
    }

}
