package com.knecon.fforesight.service.layoutparser.processor.model.text;

import java.util.HashMap;
import java.util.Map;

import lombok.Getter;

public class StringFrequencyCounter {

    @Getter
    private final Map<String, Integer> countPerValue = new HashMap<>();


    public void add(String value) {

        if (!countPerValue.containsKey(value)) {
            countPerValue.put(value, 1);
        } else {
            countPerValue.put(value, countPerValue.get(value) + 1);
        }
    }


    public void addAll(Map<String, Integer> otherCounter) {

        for (Map.Entry<String, Integer> entry : otherCounter.entrySet()) {
            if (countPerValue.containsKey(entry.getKey())) {
                countPerValue.put(entry.getKey(), countPerValue.get(entry.getKey()) + entry.getValue());
            } else {
                countPerValue.put(entry.getKey(), entry.getValue());
            }
        }
    }


    public String getMostPopular() {

        Map.Entry<String, Integer> mostPopular = null;
        for (Map.Entry<String, Integer> entry : countPerValue.entrySet()) {
            if (mostPopular == null || entry.getValue() > mostPopular.getValue()) {
                mostPopular = entry;
            }
        }
        return mostPopular != null ? mostPopular.getKey() : null;
    }

}
