package com.capgemini.reports.execution.actions;

import com.capgemini.framework.common.SettingsHelper;
import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.reports.database.HibernateUtil;
import com.capgemini.reports.database.javabean.DbReport;
import com.capgemini.reports.database.javabean.DbUser;
import com.capgemini.reports.database.manager.MngUser;
import com.capgemini.reports.emailing.templates.EmailReportHelper;
import com.capgemini.reports.exceptions.InvalidInputException;
import com.capgemini.reports.exceptions.NoConfChangesException;
import com.capgemini.reports.exceptions.NotFoundException;
import com.capgemini.reports.execution.AbstractExecutionReport;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.List;

/**
 * This action sends the typical email when normal reports begin execution, end their execution, or fail.
 */
public class InteractiveEmailAction implements IPostExecutionStep, IErrorExecutionStep {
  private static final long serialVersionUID = -2216273173886557249L;

  private static final String DOWNLOAD_URL_SERVLET = "kurt-web/downloadServlet?reportUid=";
  private static final String DOWNLOAD_URL_ROOT = SettingsHelper.getDownloadUrlRoot();
  private static final String INTERNAL_ERROR_MESSAGE = "An internal error occurred while performing the report<br>";

  @Override
  public <T extends AbstractExecutionReport<T, ?>> void performPostAction(TcSession tcSession, T report, DbReport dbReport, String fileNameWithExtension) throws NotFoundException {
    // All the users who requested this report, at this time of the execution: END
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
      List<DbUser> ownersAtReportEnd = new MngUser().searchReportOwners(session, dbReport);
      EmailReportHelper.sendEndEmail(DOWNLOAD_URL_ROOT + DOWNLOAD_URL_SERVLET + dbReport.getReportUid(), report, ownersAtReportEnd);
    }
    finally {
      session.close();
    }
  }

  @Override
  public void performTechnicalErrorAction(AbstractExecutionReport<?, ?> report, List<DbUser> owners, Throwable theOriginalException) {
    EmailReportHelper.sendErrorEmail(INTERNAL_ERROR_MESSAGE, report, owners);
    EmailReportHelper.sendErrorEmailToAdminsReport(INTERNAL_ERROR_MESSAGE, report);
  }

  @Override
  public void performFunctionalErrorAction(AbstractExecutionReport<?, ?> report, List<DbUser> owners, NoConfChangesException theOriginalException) {
    // Nothing to do in this case
  }

  @Override
  public void performFunctionalErrorAction(AbstractExecutionReport<?, ?> report, List<DbUser> owners, InvalidInputException theOriginalException) {
    EmailReportHelper.sendErrorEmail(theOriginalException.getErrorMessageForUser(), report, owners);
  }
}
