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

import com.capgemini.reports.common.scheduling.view.SchedulingParametersReader;
import com.capgemini.reports.database.HibernateUtil;
import com.capgemini.reports.database.javabean.enumeration.SchedulingEnum;
import com.capgemini.reports.database.manager.MngSchedulingCriteriaVal;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.capgemini.reports.exceptions.InvalidInputException;
import com.capgemini.reports.periodicity.PeriodFactory;
import com.capgemini.reports.periodicity.SchedulingPeriod;
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 for periodicity data.<br>
 * Receives http requests with URL parameters:
 * <ul>
 * <li>subPeriod={SUB_PERIOD} The period that is currently selected (daily/weekly/monthly/date)</li>
 * <li>isUpdate={BOOLEAN} True if an existing scheduling is being update (existing values should be retreived in DB), false if it is a brand new scheduling.</li>
 * <li>id={ID} (OPTIONAL) the identifier of the updating report, only present if isUpdate is <code>true</code></li>
 * </ul>
 */
@Slf4j
@WebServlet("/getScheduling")
public class SchedulingPeriodReaderServlet extends AbstractActionManager {
  private static final long serialVersionUID = 6495163507120953894L;
  private static final String SUCESS_MESSAGE = ""; // No need for a message to the user, it is sufficient to simply update the page

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

  /* Return sub period of current period */
  private JSONObject getSubPeriod(final HttpServletRequest request) throws InsufficientParametersException, InvalidInputException {
    String subPeriod = getMandatoryArg(request, "subPeriod");
    String isUpdateStr = getMandatoryArg(request, "isUpdate");
    Boolean isUpdate = Boolean.valueOf(isUpdateStr);
    SchedulingPeriod period;
    if (isUpdate) {
      String schedulingIdStr = getMandatoryArg(request, "id");
      Long schedulingId = Long.valueOf(schedulingIdStr);
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();
      try {
        period = new MngSchedulingCriteriaVal().getPeriod(session, schedulingId);
      }
      finally {
        session.close();
      }
    }
    else {
      period = PeriodFactory.daily();
    }
    log.info("subPeriod {} active={} id={}", subPeriod, isUpdate, period.toString());
    SchedulingEnum periodicity = SchedulingEnum.getEnum(subPeriod);
    String content = new SchedulingParametersReader().getSubPeriod(periodicity, period, isUpdate);
    log.info("Content [" + content + "]");

    return successMessage(SUCESS_MESSAGE).put("content", content);
  }
}
