package com.capgemini.reports.execution.actions;

import com.capgemini.framework.common.activedirectory.ActiveDirectory;
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 lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/** An {@link IErrorExecutionStep} that sends an email containing a link for re-launching the report. */
@Slf4j
@AllArgsConstructor
@EqualsAndHashCode
public class ReLaunchEmailAction implements IErrorExecutionStep {

    private static final long serialVersionUID = 4317516668621824636L;

    private static final String INTERNAL_ERROR_MESSAGE = "An internal error occurred while performing the report<br>";

    private final String requestURL;

    @Override
    public void performTechnicalErrorAction(final AbstractExecutionReport<?, ?> report, List<DbUser> owners, Throwable theOrginalException) {
        EmailReportHelper.sendWorkflowErrorEmail(INTERNAL_ERROR_MESSAGE, report, owners, requestURL);

        // Send email to all admins report
        List<DbUser> adminReports = ActiveDirectory.getAdminsReportUpdateDatabase();

        if (adminReports == null || adminReports.isEmpty()) {
            log.error("The request for recovery of the admins report from active directory of SNECMA has returned nothing, on fail {} ",
                    report.getReportIdentifier());
        } else {
            EmailReportHelper.sendWorkflowErrorEmailToAdminsReport(INTERNAL_ERROR_MESSAGE, report, adminReports, requestURL);
        }
    }

    @Override
    public void performFunctionalErrorAction(AbstractExecutionReport<?, ?> report, List<DbUser> owners, NoConfChangesException theOriginalException) {
        // This is a workflow execution, there are no 'functional' errors.
        // Forward email handling to Technical error handler:
        performTechnicalErrorAction(report, owners, theOriginalException);
    }

    @Override
    public void performFunctionalErrorAction(AbstractExecutionReport<?, ?> report, List<DbUser> owners, InvalidInputException theOriginalException) {
        // This is a workflow execution, there are no 'functional' errors.
        // Forward email handling to Technical error handler:
        performTechnicalErrorAction(report, owners, theOriginalException);
    }
}
