package com.capgemini.reports.r20;

import com.capgemini.reports.common.AbstractSubmitServlet;
import com.capgemini.reports.definition.r20report.Classe;
import com.capgemini.reports.definition.r20report.ConjointUnique;
import com.capgemini.reports.definition.r20report.ExecutionR20;
import com.capgemini.reports.definition.r20report.MajorMinor;
import com.capgemini.reports.reports.parameters.ProductUnit;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Servlet which manage the launch of a R20 report.<br>
 * Open a session, extract the parameters of the URL then put the report in the queue.
 *
 */
@WebServlet("/report_r20/submit")
public class SubmitServletR20 extends AbstractSubmitServlet<ExecutionR20> {

    private static final long serialVersionUID = 6996483417531940752L;
    private static final String LMR_SEPARATOR = ";"; // A semicolon (;) character

    @Override
    public ExecutionR20 prepareReport(final HttpServletRequest request) {
        // Obtain report parameters
        String product = request.getParameter("product_id");
        String unitBefore = request.getParameter("unit_before");
        String unitAfter = request.getParameter("unit_after");
        String matricule = request.getParameter("matricule");
        String classeStr = request.getParameter("classe");
        String majorMinorStr = request.getParameter("major_minor");
        String conjointUniqueStr = request.getParameter("conjoint_unique");
        String allLmrs = request.getParameter("LMR");

        // Obtain a list of all the LMRs
        List<String> lmrList = retrieveEachLMR(allLmrs);

        // Parse the result, to construct an ExecutionR20
        Classe classe = Classe.parse(classeStr);
        MajorMinor majorMinor = MajorMinor.parse(majorMinorStr);
        ConjointUnique conjointUnique = ConjointUnique.parse(conjointUniqueStr);
        ProductUnit productUnitBefore = new ProductUnit(product, unitBefore);
        ProductUnit productUnitAfter = new ProductUnit(product, unitAfter);

        return new ExecutionR20(productUnitBefore, productUnitAfter, matricule, lmrList, classe, majorMinor, conjointUnique);

    }

    // From IHM
    private static List<String> retrieveEachLMR(final String allLmrs) {
        List<String> lmrList = new ArrayList<>();
        if (allLmrs != null) {
            String[] list = allLmrs.split(LMR_SEPARATOR);
            Collections.addAll(lmrList, list);
        }
        return lmrList;
    }
}
