package com.capgemini.reports.execution.actions;

import com.capgemini.framework.common.SettingsHelper;
import com.capgemini.framework.common.activedirectory.ActiveDirectory;
import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.reports.database.javabean.DbReport;
import com.capgemini.reports.database.javabean.DbUser;
import com.capgemini.reports.emailing.templates.EmailReportHelper;
import com.capgemini.reports.exceptions.InvalidInputException;
import com.capgemini.reports.exceptions.NoConfChangesException;
import com.capgemini.reports.execution.AbstractExecutionReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * This action is similar to {@link InteractiveEmailAction}, but for scheduled reports, where mail title etc. are slightly different. <br>
 * PArticularly, owners of a report are not considered, the emails are sent to the administrators.
 */
public class ScheduledEmailAction implements IPostExecutionStep, IErrorExecutionStep {
  private static final long serialVersionUID = -2216273173886557249L;

  private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledEmailAction.class);
  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 session, T report, DbReport dbReport, String fileNameWithExtension) {
    String downloadURLroot = SettingsHelper.getDownloadUrlRoot();
    List<DbUser> ownersAtReportEnd = ActiveDirectory.getAdminsReportUpdateDatabase();
    EmailReportHelper.sendScheduledEndEmail(downloadURLroot + "kurt-web/downloadServlet?reportUid=" + report.getReportTechnicalUid(), report, ownersAtReportEnd, report.getSchedulingName());
  }

  @Override
  public void performTechnicalErrorAction(AbstractExecutionReport<?, ?> report, List<DbUser> owners, Throwable theOriginalException) {
    LOGGER.error("A Technical error occured", theOriginalException);
    EmailReportHelper.sendScheduledErrorEmailToAdminsReport(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.sendScheduledErrorEmail(theOriginalException.getErrorMessageForUser(), report, owners);
  }
}
