package com.capgemini.reports.r13;

import com.capgemini.reports.common.AbstractSubmitServlet;
import com.capgemini.reports.definition.r13report.execution.AbstractExecutionR13;
import com.capgemini.reports.definition.r13report.execution.ExecutionR13CR;
import com.capgemini.reports.definition.r13report.execution.ExecutionR13FPP;
import com.capgemini.reports.reports.parameters.EffectivityDate;

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

/**
 * This class receives demands to perform a R13 report.<br>
 * It prepares the data and creates the appropriate {@link ExecutionR13CR} instance if the selected type object is "CR" or {@link ExecutionR13FPP} instance if it is "FPP".<br>
 * The execution will carry out the job.
 *
 * @param <T> a subtype of {@link AbstractExecutionR13}
 */
@WebServlet("/report_r13/submit")
public class SubmitServletR13<T extends AbstractExecutionR13<T, ?>> extends AbstractSubmitServlet<T> {

    private static final long serialVersionUID = 6034599018215480837L;

    @Override
    public T prepareReport(final HttpServletRequest request) {
        // Get the parameters
        String typeObjet = request.getParameter("type_objet");
        String dateDebutStr = request.getParameter("date_debut");
        String dateFinStr = request.getParameter("date_fin");
        // Config the dates
        EffectivityDate previousDate = (dateDebutStr.isEmpty()) ? null : new EffectivityDate(dateDebutStr);
        EffectivityDate finalDate = (dateFinStr.isEmpty()) ? new EffectivityDate() : new EffectivityDate(dateFinStr);

        // Initializing and sending report to the queues
        if ("CR".equals(typeObjet)) {
            return downCastCR(new ExecutionR13CR(finalDate, previousDate));
        } else {
            return downCastCR(new ExecutionR13FPP(finalDate, previousDate));
        }
    }

    @SuppressWarnings("unchecked")
    private <K extends AbstractExecutionR13<K, ?>> T downCastCR(final K toBeCastToCR) {
        return (T) toBeCastToCR;
    }
}
