package com.capgemini.reports.formatting;

import java.util.Collection;

/**
 * Creates a js array easily.<br>
 * Example output:<br>
 * var tab = new Array();\n<br>
 * tab[0] = 'toto';\n<br>
 * tab[1] = 'tata';\n
 */
public class JsArrayCreator {

    private final StringBuilder content = new StringBuilder();
    private final String tableName;
    private int lineCount;

    /**
     * Creates a js array wit hthe provided name.
     * 
     * @param tableName the name of the table
     */
    public JsArrayCreator(final String tableName) {
        this.tableName = tableName;
        this.content.append("\n").append("var ").append(tableName).append(" = new Array();\n");
        this.lineCount = 0;
    }

    /**
     * Add an entry to the table (will add a new line to the array).
     * 
     * @param entry the content
     */
    public void addEntry(final String entry) {
        content.append(tableName).append('[').append(lineCount).append("] = '").append(entry).append("';\n");
        lineCount++;
    }

    /**
     * Adds the provided beans' content to a line in the table.
     * 
     * @param someObjects a {@link Collection} of JAVA objects, on which {@link Object#toString() toString} will be invoked
     */
    public void addAll(final Collection<?> someObjects) {
        for (Object aBean : someObjects) {
            addEntry(aBean.toString());
        }
    }

    @Override
    public String toString() {
        return content.toString();
    }

}
