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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.Getter;

@Getter
public class FloatFrequencyCounter {

    Map<Float, Integer> countPerValue = new HashMap<>();


    public void add(float value) {

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


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

        for (Map.Entry<Float, 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 Float getMostPopular() {

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


    public List<Float> getHighterThanMostPopular() {

        Float mostPopular = getMostPopular();
        List<Float> higher = new ArrayList<>();
        for (Float value : countPerValue.keySet()) {
            if (value > mostPopular) {
                higher.add(value);
            }
        }

        return higher.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
    }


    public Float getHighest() {

        Float highest = null;
        for (Float value : countPerValue.keySet()) {
            if (highest == null || value > highest) {
                highest = value;
            }
        }
        return highest;
    }

}
