package com.capgemini.reports.formatting;

import com.capgemini.framework.common.StringHelper;
import com.capgemini.reports.database.manager.MngReport;
import com.capgemini.reports.database.manager.MngReport.RunningReportEntry;
import com.capgemini.reports.exceptions.NothingToBeShownException;
import org.apache.commons.lang.StringEscapeUtils;
import org.hibernate.Session;

import java.util.List;

/** This class can generate an html page showing every reports currently running. */
public final class RunningReports extends AbstractTableFormatter {

    private static final String END = "';";

    @Override
    protected String makeTable(Session session) throws NothingToBeShownException {
        StringBuilder theTableCode = new StringBuilder("var reportArray = new Array();\n");
        List<RunningReportEntry> runningReports = new MngReport().searchRunningReports(session);
        if (runningReports.isEmpty()) {
            throw new NothingToBeShownException("Not running reports to be displayed", "Aucun rapport en cours");
        }
        int theLineCount = 0;
        for (RunningReportEntry currentReport : runningReports) {
            String tableDeclaration = "\treportArray[" + theLineCount + "]";
            theTableCode.append(StringHelper.toJs(tableDeclaration, currentReport.getReport()));
            String safename = currentReport.getSafeName();
          theTableCode.append(tableDeclaration).append("['login'] = '").append(StringEscapeUtils.escapeJavaScript(safename)).append(END);
            theTableCode.append(tableDeclaration).append("['priority'] = '").append(currentReport.getReportPriority()).append(END);
            theTableCode.append(tableDeclaration).append("['requestDate'] = '").append(currentReport.getRequestDate()).append(END);
            theTableCode.append('\n');
            theLineCount++;
        }
        return theTableCode.toString();
    }

    @Override
    protected String successPageTemplateLocation() {
        return "/html/runningReports/running_reports_success.html";
    }

    @Override
    protected String failedPageTemplateLocation() {
        return "/html/runningReports/running_reports_failed.html";
    }

    @Override
    protected void addOptionalTags(Session session) {
        // Nothing to do for Running Reports
    }

    @Override
    protected void addOptionalErrorTags() {
        // Nothing to do for Running Reports
    }
}
