package org.academiadecodigo.enuminatti.wordhistogram;

import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class HistogramMap extends LinkedHashMap<String, Integer>
        implements Iterable<String> {

    private int biggestWord = 0;

    public void add(String key) {
        if (putIfAbsent(key, 1) == null) {
            biggestWord = (key.length() > biggestWord) ?
                    key.length() : biggestWord;
        } else {
            put(key, get(key) + 1);
        }
    }

    public void addAll(String[] keys) {
        for (String key : keys) {
            add(key);
        }
    }

    @Override
    public Iterator<String> iterator() {
        return keySet().iterator();
    }

    @Override
    public String toString() {

        for (String word : keySet()) {
            biggestWord = (word.length() > biggestWord) ? word.length() : biggestWord;
        }

        int length = biggestWord + 8;

        StringBuilder res = new StringBuilder();
        res.append("Used | Word\n");
        for (int i = 0; i < length; i++) {
            res.append('=');
        }
        res.append("\n");
        for (String word : keySet()) {
            res.append(String.format("%4d | %s\n", get(word), word));
        }
        return res.toString();
    }
}
