package cn.com.qmth.stmms.biz.report.utils.unit;

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

public class RangeCounter {

    public int totalCount;

    public double interval;

    public Map<Double, Integer> GeAndLtMap;

    public Map<Double, Integer> GtAndLeMap;

    public RangeCounter() {
        this.interval = 1;
        this.GeAndLtMap = new HashMap<Double, Integer>();
        this.GtAndLeMap = new HashMap<Double, Integer>();
    }

    public void process(double score) {
        totalCount++;
        // 取最接近的分段起始分数
        double min = score;
        while ((min + interval) < score) {
            min += interval;
        }
        // 以起始分数为key，累加计数结果
        Integer count = GeAndLtMap.get(min);
        if (count == null) {
            count = 0;
        }
        count++;
        GeAndLtMap.put(min, count);

        // 计算(s1, s2]
        double max = score;
        while ((max - interval) > score) {
            max -= interval;
        }
        Integer count1 = GtAndLeMap.get(max);
        if (count1 == null) {
            count1 = 0;
        }
        count1++;
        GtAndLeMap.put(max, count1);
    }

    /**
     * 获取在[s1, s2)分数范围内的数量<br>
     * s1和s2可以有一个为null，不能全部为null
     * 
     * @param s1
     * @param s2
     * @return
     */
    public int countGeAndLt(Double s1, Double s2) {
        int count = 0;
        if (s1 != null || s2 != null) {
            for (Entry<Double, Integer> entry : GeAndLtMap.entrySet()) {
                Double key = entry.getKey();
                if (s1 != null && key < s1) {
                    continue;
                }
                if (s2 != null && key >= s2) {
                    continue;
                }
                count += entry.getValue();
            }
        }
        return count;
    }

    /**
     * 获取在(s1, s2]分数范围内的数量<br>
     * s1和s2可以有一个为null，不能全部为null
     * 
     * @param s1
     * @param s2
     * @return
     */
    public int countGtAndLe(Double s1, Double s2) {
        int count = 0;
        if (s1 != null || s2 != null) {
            for (Entry<Double, Integer> entry : GtAndLeMap.entrySet()) {
                Double key = entry.getKey();
                if (s1 != null && key <= s1) {
                    continue;
                }
                if (s2 != null && key > s2) {
                    continue;
                }
                count += entry.getValue();
            }
        }
        return count;
    }
}
