package com.capgemini.reports.database.stats;

import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

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

    private static final String TOTAL = "total";

    /**
     * HTML entity for blank character.
     **/
    private static final String BLANK_CHAR = "&nbsp;";

    private String name;
    private Map<String, String> datas = new TreeMap<>();

    /**
     * Make a simple bean containing stats about a user.
     *
     * @param name the user name
     */
    public UserStatBean(final String name) {
        this.name = name;
    }

    /**
     * Convert the current bean by Javascript code.
     *
     * @param aJsArrayName Name of the JAVA script array
     * @return The Javascript code
     */
    public String toJs(final String aJsArrayName) {
        StringBuilder theJsCodeBuilder = new StringBuilder(aJsArrayName).append(" = new Array();\n");
        theJsCodeBuilder.append(aJsArrayName).append("['name'] = \"").append(nullAsBlank(name)).append("\";\n");
        for (Entry<String, String> entry : datas.entrySet()) {
            if (entry.getKey().equals(TOTAL)) {
                theJsCodeBuilder.append(aJsArrayName).append("['Global'] = '").append(nullAsBlank(entry.getValue())).append("';\n");
            } else {
                theJsCodeBuilder.append(aJsArrayName).append("['").append(entry.getKey()).append("'] = '").append(nullAsBlank(entry.getValue())).append("';\n");
            }
        }
        return theJsCodeBuilder.toString();
    }

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

    @Override
    public String toString() {
        return "UserStatBean [name=" + name + ", datas=" + datas + "]";
    }
}
