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

import com.capgemini.framework.teamcenter.exceptions.KurtException;
import com.capgemini.reports.database.HibernateUtil;
import com.capgemini.reports.database.manager.MngReportType;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.capgemini.reports.exceptions.InvalidInputException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.json.JSONObject;

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

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

  private static final long serialVersionUID = -3288930443279088612L;

  private static final String SUCESS_MESSAGE_IS_AUTHORIZED = "La demande a bien &eacute;t&eacute; prise en compte";
  private static final String ERROR_MESSAGE_IS_AUTHORIZED = "Le lancement de ce rapport n&apos;est pas autoris&eacute;";

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

  private JSONObject isAuthorizedReport(final HttpServletRequest request) throws InsufficientParametersException {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
      MngReportType mngReportType = new MngReportType();
      if (mngReportType.isAuthorized(session, getMandatoryArg(request, URL_KEY_REPORT_CODE))) {
        return successMessage(SUCESS_MESSAGE_IS_AUTHORIZED);
      }
      else {
        return errorMessage(new KurtException(ERROR_MESSAGE_IS_AUTHORIZED));
      }
    }
    finally {
      session.close();
    }
  }
}
