package com.capgemini.reports.common.scheduling;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.reports.common.ServletMessageHelper;
import com.capgemini.reports.database.HibernateUtil;
import com.capgemini.reports.database.javabean.DbSchedulingReport;
import com.capgemini.reports.database.manager.MngSchedulingReport;
import com.capgemini.reports.exceptions.InsufficientParametersException;
import com.capgemini.reports.exceptions.NotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.json.JSONObject;
import org.quartz.SchedulerException;

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

/**
 * Class providing the framework for deleting a scheduling.
 */
@WebServlet("/scheduling/delete")
public class DeleteServletScheduling extends AbstractGenerateScheduledTemplateServlet {
  private static final long serialVersionUID = -8856096872281102308L;

  @Override
  protected JSONObject perform(final HttpServletRequest request, final TcSession tcSession) throws SchedulerException, NotFoundException, InsufficientParametersException {

    // Obtain all parameters from the request
    String schedulingReportIdStr = request.getParameter(KEY_SCHEDULING_REPORT_ID);
    Long schedulingReportId;
    if (schedulingReportIdStr == null) {
      throw new InsufficientParametersException("No scheduling Identifier passed to DeleteServletScheduling, aborting...");
    }
    try {
      schedulingReportId = Long.valueOf(schedulingReportIdStr);
    }
    catch (NumberFormatException e) {
      throw new InsufficientParametersException("Input scheduling Identifier passed to DeleteServletScheduling could not be understood: "
        + schedulingReportIdStr, e);
    }

    // Delete the Job and all of its triggers
    schedulingServer.deleteScheduledJobAndKeys(schedulingReportId);

    // Update the DB
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
      MngSchedulingReport mngSchedulingReport = new MngSchedulingReport();
      DbSchedulingReport report = mngSchedulingReport.searchById(session, schedulingReportId);
      mngSchedulingReport.deleteSchedulingReport(schedulingReportId);

      // Return a success message
      return successMessage(report.getReportCode());
    }
    finally {
      session.close();
    }
  }

  private JSONObject successMessage(final String reportCode) {
    return ServletMessageHelper.successMessage("Le rapport \"" + reportCode + "\" a bien été supprimé");
  }
}
