urns {string} The formatted string, pluralized where necessary
 */
function renderSummary(totalErrors, totalWarnings) {
    const totalProblems = totalErrors + totalWarnings;
    let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`;

    if (totalProblems !== 0) {
        renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`;
    }
    return renderedText;
}

/**
 * Get the color based on whether there are errors/warnings...
 * @param {string} totalErrors Total errors
 * @param {string} totalWarnings Total warnings
 * @returns {int} The color code (0 = green, 1 = yellow, 2 = red)
 */
function renderColor(totalErrors, totalWarnings) {
    if (totalErrors !== 0) {
        return 2;
    }
    if (totalWarnings !== 0) {
        return 1;
    }
    return 0;
}

/**
 * Get HTML (table row) describing a single message.
 * @param {Object} it data for the message.
 * @returns {string} HTML (table row) describing the message.
 */
function messageTemplate(it) {
    const {
        parentIndex,
        lineNumber,
        columnNumber,
        severityNumber,
        severityName,
        message,
        ruleUrl,
        ruleId
    } = it;

    return `
<tr style="display: none;" class="f-${parentIndex}">
    <td>${lineNumber}:${columnNumber}</td>
    <td class="clr-${severityNumber}">${severityName}</td>
    <td>${encodeHTML(message)}</td>
    <td>
        <a href="${ruleUrl ? ruleUrl : ""}" target="_blank" rel="noopener noreferrer">${ruleId ? ruleId : ""}</a>
    </td>
</tr>
`.trimStart();
}

/**
 * Get HTML (table rows) describing the messages.
 * @param {Array} messages Messages.
 * @param {int} parentIndex Index of the parent HTML row.
 * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis.
 * @returns {string} HTML (table rows) describing the messages.
 */
function renderMessages(messages, parentIndex, rulesMeta) {

    /**
     * Get HTML (table row) describing a message.
     * @param {Object} message Message.
     * @returns {string} HTML (table row) describing a message.
     */
    return messages.map(message => {
        const lineNumber = message.line || 0;
        const columnNumber = message.column || 0;
        let ruleUrl;

        if (rulesMeta) {
            const meta = rulesMeta[message.ruleId];

            if (meta && meta.docs && meta.docs.url) {
                ruleUrl = meta.docs.url;
            }
        }

        return messageTemplate({
            parentIndex,
            lineNumber,
            columnNumber,
            severityNumber: message.severity,
            severityName: message.severity === 1 ? "Warning" : "Error",
            message: message.message,
            ruleId: message.ruleId,
            ruleUrl
        });
    }).join("\n");
}

/**
 * Get HTML (table row) describing the result for a single file.
 * @param {Object} it data for the file.
 * @returns {string} HTML (table row) describing the result for the file.
 */
function resultTemplate(it) {
    const { color, index, filePath, summary } = it;

    return `
<tr class="bg-${color}" data-group="f-${index}">
    <th colspan="4">
        [+] ${encodeHTML(filePath)}
        <span>${encodeHTML(summary)}</span>
    </th>
</tr>
`.trimStart();
}

/**
 * Render the results.
 * @param {Array} results Test results.
 * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis.
 * @returns {string} HTML string describing the results.
 */
function renderResults(results, rulesMeta) {
    return results.map((result, index) => resultTemplate({
        index,
        color: renderColor(result.errorCount, result.warningCount),
        filePath: result.filePath,
        summary: renderSummary(result.errorCount, result.warningCount)
    }) + renderMessages(result.messages, index, rulesMeta)).join("\n");
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = function(results, data) {
    let totalErrors,
        totalWarnings;

    const metaData = data ? data.rulesMeta : {};

    totalErrors = 0;
    totalWarnings = 0;

    // Iterate over results to get totals
    results.forEach(result => {
        totalErrors += result.errorCount;
        totalWarnings += result.warningCount;
    });

    return pageTemplate({
        date: new Date(),
        reportColor: renderColor(totalErrors, totalWarnings),
        reportSummary: renderSummary(totalErrors, totalWarnings),
        results: renderResults(results, metaData)
    });
};
