package com.capgemini.reports.database.stats;

import com.capgemini.framework.common.TimeHelper;
import lombok.Setter;

/**
 * Bean object carrying Statistical information about a report.
 */
@Setter
public class ReportStatBean {

    /**
     * HTML entity for blank character.
     **/
    private static final String BLANK_CHAR = "&nbsp;";
    private static final String DELIM = "-";
    private static final String ZERO_STRING = "0";
    private final String reportCode;
    private Long executionCount;
    private Long failedFuncCount;
    private Long failedTechCount;
    private Long minDuration;
    private Long avgDuration;
    private Long maxDuration;

    /**
     * Makes an ReportStatBean, using its code as a reference.
     *  @param aReportCode  a report code (R' etc.)
     *
     */
    public ReportStatBean(final String aReportCode) {
        this.reportCode = aReportCode;
    }

    /**
     * Convert the current bean by Javascript code.
     *
     * @param aJsArray Name of the JAVA script array
     * @return The Javascript code
     */
    public String toJs(final String aJsArray) {
        return aJsArray + " = new Array();\n" +
                aJsArray + "['reportCode'] = '" + nullAsBlank(reportCode) + "';\n" +
                aJsArray + "['executionCount'] = '" + nullAsBlank(executionCount) + "';\n" +
                aJsArray + "['failedFuncCount'] = '" + nullAsBlank(failedFuncCount) + "';\n" +
                aJsArray + "['failedTechCount'] = '" + nullAsBlank(failedTechCount) + "';\n" +
                aJsArray + "['minDuration'] = '" + TimeHelper.formatDuration(minDuration) + "';\n" +
                aJsArray + "['avgDuration'] = '" + TimeHelper.formatDuration(avgDuration) + "';\n" +
                aJsArray + "['maxDuration'] = '" + TimeHelper.formatDuration(maxDuration) + "';\n";
    }

    public String toCsv() {
        return reportCode + ","
                + contentOrZero(executionCount) + ","
                + contentOrZero(failedFuncCount) + ","
                + contentOrZero(failedTechCount) + ","
                + contentOrZero(minDuration) + ","
                + contentOrZero(avgDuration) + ","
                + contentOrZero(maxDuration);
    }

    private String contentOrZero(final Long exec) {
        return exec == null ? ZERO_STRING : exec.toString();
    }

    /**
     * Display null values with a blank character.
     *
     * @param value Value which should be converted.
     * @return The string value.
     */
    private String nullAsBlank(final Object value) {
        return value == null ? BLANK_CHAR : value.toString();
    }


    @Override
    public String toString() {
        return "ReportStatBean [reportCode=" + reportCode + ", executionCount=" + executionCount + ", failedFuncCount=" + failedFuncCount
                + ", failedTechCount=" + failedTechCount + ", minDuration=" + minDuration + ", avgDuration=" + avgDuration + ", maxDuration="
            + maxDuration + "]";
    }


}
