package com.capgemini.reports.common.scheduling.utilities;

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

import org.json.JSONObject;

import com.capgemini.reports.database.javabean.DbReportType;
import com.capgemini.reports.database.manager.MngReportType;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.capgemini.reports.exceptions.InvalidInputException;

import lombok.extern.slf4j.Slf4j;

/**
 * Servlet handling requests to chachge activation status of the report in DB.<br>
 * Receives http requests with URL parameters:
 * <ul>
 * <li>reportCode={REPORT_CODE}</li>
 * <li>reportAuthorized={AUTHORIZATION}</li>
 * </ul>
 * Example:<br>
 * {@code kurt-web/activateDeactivate?reportCode=R01&reportAuthorized=true}
 */
@Slf4j
@WebServlet("/activateDeactivate")
public class ReportActivatorServlet extends AbstractActionManager {

    private static final long serialVersionUID = 403605177414500576L;

    private static final String URL_KEY_REPORT_AUTHORIZED = "reportAuthorized";

    @Override
    protected JSONObject perform(final HttpServletRequest request, final HttpServletResponse response)
            throws InsufficientParametersException, InvalidInputException {
        log.info("Start Manager scheduling Report ....");
        return enableDisableAuthorizedReport(request);
    }

    /*Save or Unsaved scheduling report  */
    private JSONObject enableDisableAuthorizedReport(final HttpServletRequest request) throws InsufficientParametersException {
        String reportCode = getMandatoryArg(request, URL_KEY_REPORT_CODE);
        String reportAuthorized = getMandatoryArg(request, URL_KEY_REPORT_AUTHORIZED);

        log.info("Update {} activation with value {}", reportCode, reportAuthorized);

        DbReportType dbReportType = new MngReportType().setReportActivation(reportCode, reportAuthorized);

        return successMessage("La modification a bien &eacute;t&eacute; prise en compte pour le rapport " + dbReportType.getTitle());
    }

}
